简体   繁体   中英

How can I take the data to Array ReactJS?

I fetch data from an api and data takes successfully but there is a problem when I determine the data to an array. Array doesn't assign the data.

 const [Profile,setProfile]=useState([]);//I created array state here
  const [username,setUsername]=useState('');
  const [password,setPassword]=useState('');
  const [logout,setLogout]=useState(0);
  useEffect(() => {
    return () => {
      console.log(Profile);
    }
  }, [Profile.length])
  const login = () => {
    
    var myHeaders = new Headers();
    myHeaders.append("Content-Type", "application/json");
    myHeaders.append("Access-Control-Allow-Origin","*");
    myHeaders.append('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,PATCH,OPTIONS');
    var raw = JSON.stringify({username, password});
    
    var requestOptions = {
      method: 'POST',
      headers: myHeaders,
      body: raw,
      redirect: 'follow'
    };
    
    fetch("http://localhost/scheduleapp/api/personals/login", requestOptions)
      .then(response => response.text())
      .then(response =>{setProfile(response) ;console.log(response); localStorage.setItem('Logged',response)})//here response is seen console and setted to local storage with success but setstate doesnt work
      .catch(error => console.log('error', error));
      
      
  }

As I say setstate doesnt set data to array

If you want to add an array to your state. First you can give that state an empty array as an initial value. Example - const [ data, setdata] = useState([]) After that you can destructor your response and assign them one by one to the array like this

setdata(... response)

Make sure the response is an array.

The problem with the profile state, you need to renamed it to 'profile' instead of 'Profile' because React assuming is a component for the capitalization, that's why it never assigns the value to the state.

for Example:

const [profile,setProfile]=useState([]);

instead of this:

const [Profile,setProfile]=useState([]);

Other important detail is how you are using the 'useEffect' for example when you are console.log the results is when the component is unmounted, to make sure you are setting the value put it outside the useEffect to see if the state is changing like this:

useEffect(() => {
    return () => {
      console.log(Profile);
    }
}, [Profile.length])

use like this:

useEffect(() => {
    // call your function here if you want to execute when the component is mounted.
}, []);
console.log(profile);

use response.json() instead of response.text() and for storing the response in the localStorage use localStorage.setItem(JSON.stringify(response))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM