Search code examples
javascriptreactjssetstateuse-state

how to refresh component in react js


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


Solution

  • 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