Home > Net >  Everytime i press my button, i want it to create a new div with the new data, but it just change the
Everytime i press my button, i want it to create a new div with the new data, but it just change the

Time:12-23

I have a fetchapi button that gets me a new address everytime i press it, and it show the data in the fields. I want that everytime i press the fetch api button, it adds a new div and the new address without deleting the old one:

  const fetchapi = async () => {
    try {
      setLoading(true);
      await axios
        .get("https://random-data-api.com/api/v2/addresses")
        .then((response) => {
          setAllData(response.data);

          console.log(response.data);
        });
    } catch (error) {
      setLoading(false);
      console.log(error);
    }
  };

  return (
    <Fragment>
      <div>
        <button onClick={fetchapi}>Fetch Location</button>
        {!allData ? null : (
          <div
            style={{
              backgroundColor: "#c7c7c7",
              display: "flex",
              flexDirection: "column",
              padding: 16,
              margin: 5,
              borderRadius: 20
            }}
          >
            <p>
              <strong>Address: {allData.street_address}</strong>
            </p>
            <p>
              <strong>City: {allData.city}</strong>
            </p>
            <p>
              <strong>Street Name: {allData.street_name}</strong>
            </p>
            <p>
              <strong>Zipcode: {allData.zip_code}</strong>
            </p>
            <button onClick={removeElement}>remove</button>
          </div>
        )}
      </div>
    </Fragment>
  );
};

it already fetch the data and remove it if i press the remove button. if someone can help me, would much appreciate it.

CodePudding user response:

You are maintaining your state as object so whenever new data comes in you're just changing the state with it.

if you want to retain old data also in the page, you have to maintain an array in state.

setAllData([...allData, response.data]);

and then render the array with map

<Fragment>
  <div>
    <button onClick={fetchapi}>Fetch Location</button>
    {allData.map((data,index)=>(
      <div
        style={{
          backgroundColor: "#c7c7c7",
          display: "flex",
          flexDirection: "column",
          padding: 16,
          margin: 5,
          borderRadius: 20
        }}
      >
        <p>
          <strong>Address: {data.street_address}</strong>
        </p>
        <p>
          <strong>City: {data.city}</strong>
        </p>
        <p>
          <strong>Street Name: {data.street_name}</strong>
        </p>
        <p>
          <strong>Zipcode: {data.zip_code}</strong>
        </p>
        <button onClick={removeElement}>remove</button>
      </div>
    ))}
  </div>
</Fragment>
  • Related