7

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.

2
  • what does your console.log show after your let test = await response.json()? Commented Jun 8, 2020 at 15:59
  • I get an array like this ['cars','boat','bike'] Commented Jun 8, 2020 at 16:10

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! like you said I 'console.log' the 'state' in the wrong place.
0

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.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.