using map in useeffect

Solutions on MaxInterview for using map in useeffect by the best coders in the world

showing results for - "using map in useeffect"
Madalyn
11 Jun 2020
1useEffect(async () => {
2    try{ 
3      let response = await axios.get(`https://swapi.co/api/people/`)
4      let data = await response.json();
5      let newState = data.map((e) => e); // map your state here
6      setChars(newState); // and then update the state
7      console.log(newState);
8    } catch(error) {
9       console.error(error.message);
10    }
11  },[]);
Nicolás
17 Mar 2017
1import React, { useState, useEffect } from 'react';
2import axios from 'axios';
3import './App.css';
4import CharacterMap from './characterMap'
5
6const App = () => {
7  let [chars, setChars] = useState([]);
8  useEffect(async () => {
9    try{ 
10      let response = await axios.get(`https://swapi.co/api/people/`)
11      let data = await response.json();
12      setChars(data);
13    } catch(error) {
14       console.error(error.message);
15    }
16  },[]);
17 // If you want to access the updated state then use this.
18  useEffect(() => {
19     let newState = chars.map((e) => e); // map your state here
20     setChars(newState); // and then update the state
21     console.log(newState);
22  },[getChars]);
23
24  return (
25
26    <div className="App">
27      <CharacterMap info={chars} />
28    </div>
29  );
30}
31export default App;
32