import React, { useState, useEffect } from 'react';
import axios from 'axios';
import List from './List';
const App = () => {
const [input, setInput] = useState('');
const [todos, setTodos] = useState([]);
const [pending, setPending] = useState(false);
const fetchInitData = async () => {
setPending(true);
const res = await axios.get('<https://koreanjson.com/todos>');
setPending(false);
setTodos(res.data);
};
useEffect(() => {
setInput('');
}, [todos]);
useEffect(() => {
fetchInitData();
}, []);
return (
<div>
<h1>todo 애플리케이션</h1>
<form action="">
<input type="text" name="" value={input} onChange={(e) => setInput(e.target.value)} />
<button type="button" onClick={() => setTodos([...todos, input])}>할일추가</button>
</form>
{pending
? 'loading...'
: <List todos={todos} />
}
</div>
);
};
export default App;
import React, { useState, useEffect } from 'react';
import axios from 'axios';
import List from './List';
const useFetch = (callback, url) => {
const [pending, setPending] = useState(false);
const fetchInitData = async () => {
setPending(true);
const res = await axios.get(url);
setPending(false);
callback(res.data);
};
useEffect(() => {
fetchInitData();
}, []);
return pending;
};
const App = () => {
const [input, setInput] = useState('');
const [todos, setTodos] = useState([]);
const pending = useFetch(setTodos, '<https://koreanjson.com/todos>');
useEffect(() => {
setInput('');
}, [todos]);
return (
<div>
<h1>todo 애플리케이션</h1>
<form action="">
<input type="text" name="" value={input} onChange={(e) => setInput(e.target.value)} />
<button type="button" onClick={() => setTodos([...todos, input])}>할일추가</button>
</form>
{pending
? 'loading...'
: <List todos={todos} />
}
</div>
);
};
export default App;
파일 분리
useFetch.js
import { useState, useEffect } from 'react';
import axios from 'axios';
const useFetch = (callback, url) => {
const [pending, setPending] = useState(false);
const fetchInitData = async () => {
setPending(true);
const res = await axios.get(url);
setPending(false);
callback(res.data);
};
useEffect(() => {
fetchInitData();
}, []);
return pending;
};
export default useFetch;