0

I am using a stateless component and got value from the json file, When I fetch data using map from json file object, then it will store only last data in state not whole objects:

import React, { useState, useEffect} from 'react'
import usersInformation from '../assets/dataconfig/users.json'

const Login = () => {

const [userEmail, updateEmail] = useState([]);
const [userPassword, updatePassword] = useState([]);

   useEffect(function () {
   const getUserdata = () => {
        usersInformation.authorizedwebusers.map(item => {
            console.log(item);
            updateEmail([...userEmail, item.emailAddress]); // here store only last json data - [email protected]
            updatePassword([...userPassword, item.emailpassword])
        })
    }
    getUserdata();

}, [])

}

My json save as users.json:

{
 "authorizedwebusers": [
    {
        "name": "Anil",
        "emailAddress": "[email protected]",
        "emailpassword": "123"
    },
    {
      "name": "Lalit",
      "emailAddress": "[email protected]",
      "emailpassword": "123"
    },
    {
        "name": "Shiv",
        "emailAddress": "[email protected]",
        "emailpassword": "123"
    }
  ]
}
1
  • Is your question how to set state in a stateless component? Or is it why only the last data saved in state? Commented Feb 7, 2020 at 18:38

1 Answer 1

1

You are doing it wrong. setXyz() is not a synchronous action, it takes some time. You need to implement this in a different way. First calculate and then set values.

useEffect(function () {
   const getUserdata = () => {
        const emails = [];
        const passwords = [];
        usersInformation.authorizedwebusers.map(item => {
            console.log(item);
            emails.push(item.emailAddress);
            passwords.push(item.emailpassword);
        });
        updateEmail([...userEmail, ...emails]);
        updatePassword([...userPassword, ...passwords])
    }
    getUserdata();

}, [])

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

Comments

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.