ed ei
ed ei

Reputation: 69

React useState keep giving me undefined

const [urlList, setUrlList] = useState();

onClick={function(){
                                setUrlList(item.num);
                                console.log(item.num);
                          
                                callDayList();
                            }}
  1. what is this code about?

there is a table, and if I click a url, it gives item.num(1,2,3...). and through the callDayList func, the number goes to backend(node.js).

  1. what is the problem?

the problem is the state urlList, does not have proper number, but only undefined. the outcome of console.log is only undefined. however, on chrome, I found that the state is changing correctly, however the speed of change bit slow and the value of state showing me the state of last click(not sure you understand, on second click, the value of state is the first click's state.).

3.what I have tried?

I have searched internet, and I think this is the problem of rendering. because useState does not apply changes immediately. and I think this is the reason keep showing me undefined, because on first click, there is no value in state(and on second click, it shows the value of state of first click.)

one of the solution was code like ...item.num (add"...") but, did not work. second was put the state in a var, like var _num = urlList and console.log(_num) but also did not work.

actually, I have already solved this problem by not using state, but put the item.num in a var and send it to backend, but I want to understand why it is not working through useState.

Upvotes: 0

Views: 652

Answers (2)

Amila Senadheera
Amila Senadheera

Reputation: 13235

setUrlList(item.num); this is asynchronous. You need to use a useEffect hook to do anything that should happen when urlList changes. Try below:

import {useEffect} from 'react';

const [urlList, setUrlList] = useState();

const callDayList = () => { 
     console.log(urlList); 
     Axios.post('localhost:3001/api/get',{ passNum : urlList, });
}

useEffect(() => {callDayList();}, [urlList]);

In your element,

onClick={function(){ setUrlList(item.num);}}

Upvotes: 1

designtocode
designtocode

Reputation: 2245

You need to watch for changes in your state. See example with your code (mock data) https://codesandbox.io/s/proud-cherry-1c8b6

useEffect is watching for the state changes of urlList

As you can also see the first console outside of the useEffect, is giving undefined.

export default function App() {
  const [urlList, setUrlList] = useState();
  const items = [1, 2, 3]
  console.log(urlList);

  useEffect(() => {
    console.log(urlList);
  }, [urlList])
  return (
    <div className="App">
      {items.map(item => {
        return (
          <p onClick={function(){
            setUrlList(item);
            console.log(item);
        }}>Item {item}</p>
        )
      })}
    </div>
  );
}

Upvotes: 1

Related Questions