Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
22
rated 0 times [  24] [ 2]  / answers: 1 / hits: 9188  / 4 Years ago, sat, may 16, 2020, 12:00:00

I use React js ,There is a variable in the App.js file called Persons.
I want the Persons value to be updated every time I click on the button.



import React from react;
import ./styles.css;
import Button from @material-ui/core/Button;
import EleventHeaderCard from ./ElevatedHeaderCard;
import axios from axios;

export let persons = [
{
id: 9,
email: [email protected],
first_name: Michael,
last_name: Lawson,
avatar: https://s3.amazonaws.com/uifaces/faces/twitter/follettkyle/128.jpg
},
{
id: 10,
email: [email protected],
first_name: Lindsay,
last_name: Ferguson,
avatar: https://s3.amazonaws.com/uifaces/faces/twitter/araa3185/128.jpg
}
];

const handleClick = () => {
return axios.get(`https://reqres.in/api/users?page=2`).then(res => {
persons = res.data.data;
console.log(persons);
});
};

export default function App() {
return (
<div className=App>
<Button color=primary type=Submit onClick={handleClick}>
click me !!!
</Button>
<EleventHeaderCard />
</div>
);
}


Here you can see my codesandbox


More From » reactjs

 Answers
9

The logic used to pass data into subComponent is wrong you have to pass it as props instead of import inside subComponent



Also in order to rerender every request you have to use the useState hook , which returns an array of yourValue and it's setter method



so use inside the app function



let [persons, setPersons] = useState(initialData);


and then in the axios result set the persons using setPersons funciton



and in your EleventHeaderCard coponent pass the person as props .



see this working pen


[#3796] Wednesday, May 13, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
agustindejonm

Total Points: 738
Total Questions: 84
Total Answers: 84

Location: Northern Ireland
Member since Mon, Nov 14, 2022
2 Years ago
agustindejonm questions
Fri, Jun 25, 21, 00:00, 3 Years ago
Fri, Sep 18, 20, 00:00, 4 Years ago
Thu, May 14, 20, 00:00, 4 Years ago
;