Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
85
rated 0 times [  89] [ 4]  / answers: 1 / hits: 24143  / 4 Years ago, mon, june 8, 2020, 12:00:00

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.


More From » reactjs

 Answers
13

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.


[#50887] Wednesday, May 27, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
karladaijahf

Total Points: 78
Total Questions: 123
Total Answers: 89

Location: Liechtenstein
Member since Wed, Dec 8, 2021
3 Years ago
;