updating array useState react hooks (Next.js)

15,677

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.

Share:
15,677
sam
Author by

sam

Updated on June 04, 2022

Comments

  • sam
    sam almost 2 years

    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.

  • sam
    sam almost 4 years
    Thank you! like you said I 'console.log' the 'state' in the wrong place.
  • Admin
    Admin over 2 years
    As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.