Reputation: 105
I am trying to update my 'state' array and insert items of type String into it with 'setState' but it doesn't works.
I know it's not work with push().
I also tried to update my 'state' array with the spread operator but it also doesn't work.
Here my code:
import React, { useState } from 'react';
import _, { debounce } from 'lodash';
export default function Search() {
const [state, setState] = useState([])
const handleChange = debounce(async (value) => {
const url = `http://localhost:3100/`
if (value == '') {
return
}
let response = await fetch(url, {
headers: {
'Content-Type': 'application/json'
},
method: 'POST',
body: JSON.stringify({ value })
})
let test = await response.json()
console.log(test)
setState(state.concat(test))
// setState([...state, test]) it also doesn't work
console.log(state)
}, 1000)
return (
<>
<div>
<input onChange={e => handleChange(e.target.value)} />
</div>
</>
)
}
The 'state' array remains empty. I need to understand why please.
Upvotes: 7
Views: 29186
Reputation: 1
https://codesandbox.io/s/next-js-infinite-scroll-3vfem?file=/pages/Content.js
I added one line to this function from the demo above
const getMorePost = async () => {
const res = await fetch(
`https://jsonplaceholder.typicode.com/todos?_start=${posts.length}&_limit=20`
);
const newPosts = await res.json()
setHasMore(!!newPosts.length)
setPosts((post) => [...post, ...newPosts])
}
now scroll completes ok.
Upvotes: 0
Reputation: 1169
1.) Change if(value == '')
to if(value ==='')
2.) console.log(state)
after your setState will return the previous value of state as the component has not refreshed yet. Look at the example here: https://codesandbox.io/s/friendly-ives-vvo13?file=/src/App.js:103-474 and type something and look at the console. Then type something else and look at the console. You will see the console is showing the state of what you previous typed. However, if you look at the {state} rendered inside of the return, it will show you the current state.
export default function App() {
const [state, setState] = useState([]);
const handleChange = debounce(async value => {
let test = ["cars", "boat", "bike"];
setState([...test, value]);
console.log(state);
}, 1000);
return (
<>
<div>
{state}
<input onChange={e => handleChange(e.target.value)} />
</div>
</>
);
}
So you are setting state, just accessing/reading it in the wrong place.
Upvotes: 4