Following is the code which is working fine on initial load time, but on clicking fetch data button its now fetching the data correctly. Let me know what I am doing wrong here.
Code -
const Sample = () => {
const [todoCount, setTodoCount] = useState(3);
const [todos, setTodos] = useState([]);
useEffect(() => {
Array(todoCount)
.fill()
.map((_x, i) => {
return axios
.get(`https://jsonplaceholder.typicode.com/todos/${i + 1}`)
.then((res) => {
const todo = res.data.title;
setTodos((prevTodos) => {
return [...prevTodos, todo];
});
});
});
}, [todoCount]);
const fetchMore = (e) => {
setTodoCount((prevCount) => prevCount + 1);
};
return (
<div className="example">
<h3>Fetch data in a loop</h3>
<ul>
{todos.map((x, i) => (
<li key={i}>{x}</li>
))}
</ul>
<button onClick={fetchMore}>Fetch More</button>
</div>
);
};
export default Sample;
CodeSandBox - https://codesandbox.io/s/black-mountain-y8xpl
Expected Result -
- Initial Load - 3 Titles
- Click "Fetch More" button it is adding 4 to the list, making it 7 instead it should be 4(increment by 1 only).