Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
145 views
in Technique[技术] by (71.8m points)

javascript - How to assign first state data to second state in react?

When i am setting the data from one state to another state. It's saying undefined. Currently i am working on tinder like card swipe functionality with Right and left button click.

I am passing the user id from card to to button. Such as Right swipe and left swipe button.

//Scenario first If have declared the array of object static, it's works like a charm, then it does not says any error.

////Scenario Second If i am setting the data dynamically with API to SetState and assigning the state variable array data to another state variable, it says undefined.

I am trying to solve this issue from 3 days, but nothing worked, i am new in React js. Help would be appreciate.

Here is my code


const AllData= [
    {
      id: 1,
      name: 'XYZ'
    },
    {
      id: 2,
      name: 'ABC'
    },
    {
      id: 3,
      name: 'ABC 2'
    },
     {
      id: 4,
      name: 'ABC 3'
    },
     {
      id: 5,
      name: 'ABC 4'
    }
  ]  //It works if set static array

const [AllData, setAllData] = useState([]); //it does not works

const GetAllUserData = async () =>{
     const bodyParameters ={
   session_id : SessionId
   };

   const {data : {data}} = await axios.post(GETALLUSER_API , bodyParameters);
   setAllData(data); 
}

// Setting current user from all data 
 const [currentUser, setCurrentUser] = useState(AllData[0])

console.log(currentUser); // undefined says 


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here, AllData will be added to the state after the GetAllUserData is done executing, it is asynchronous function, so AllData will be available after some time, you have to update the currentUser you have to do like this.

useEffect(() => {
  if (AllData.length) {
    setCurrentUser(AllData[0]);
  }
}, [AllData]);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...