Home > database >  How to call api from each of the element rendered
How to call api from each of the element rendered

Time:05-04

I wonder if calling api for every element rendering is possible. The code below didn't work for me.

export default function App() {
  const items = [
    { title: 1, description: "description1" },
    { title: 2, description: "description2" }
  ];

  const finalTitleByApi = async (title) => {
    const response = await fetch(
      `https://jsonplaceholder.typicode.com/todos/${title}`
    ).then((response) => response.json());

    return response;
  };

  return (
    <div>
      {items.map((item) => {
        return (
          <p>
            {finalTitleByApi(item.title).title}
          </p>
        );
      })}
    </div>
  );
}

What is wrong with the code above. Any help is will be appreciated. Thank you.

This is the example codesandbox link https://codesandbox.io/s/for-each-rendered-element-that-calls-api-pmcnn6?file=/src/App.js:879-886

CodePudding user response:

To trigger the async function use useEffect to invoke it during initial rendering of the component as follows. Additionally, you can use a state to manage it as well.

  const [responseState, setResponseState] = useState(null);

  const finalTitleByApi = async () => {
    const response = await fetch(
      "https://jsonplaceholder.typicode.com/todos/1"
    ).then((response) => response.json());

    console.log("Response: ", response);

    setResponseState(response);
  };

  useEffect(() => {
    finalTitleByApi();
  }, []);

  useEffect(() => {
    console.log("Response State: ", responseState);
  }, [responseState]);

CodePudding user response:

One solution that I think is

import React, { useEffect } from "react";
import "./styles.css";

import {useApplicationContext} from './Context';
export default function App() {
  const {titles, setTitles} = useApplicationContext();
  const items = [
    { title: "1", description: "description1" },
    { title: "5", description: "description2" },
    { title: "8", description: "description2" },
    { title: "9", description: "description2" },
    { title: "10", description: "description2" },
    { title: "24", description: "description2" }
  ];

  
  const makeDivs = () => {
    let a = {};
    items.map(async (item) => {
      const res = await fetch(
        `https://jsonplaceholder.typicode.com/todos/${item.title}`
      ).then(response => response.json());
      a[item.title] = res.title;
      setTitles((prevState) => {
        return {...a}
      });
    })
  }

  React.useEffect(()=> {
    makeDivs()
  }, [])

  
  // console.log(a )
  return (
    <div>
      {JSON.stringify(titles)}
      {items.map((item, index) => {
        return (
          <p
            key={Math.random()}
            style={{
              color: "black",
              backgroundColor: "yellow",
              height: 400,
              width: 400
            }}
          >
             <span>index: {item.title} {titles && titles[item.title]}</span>
          </p>
        );
      })}
    </div>
  );
}

used Context provider for not re-render component state link of sandbox is Sandbox

  • Related