Home > Enterprise >  I have a json data and I wanted to know how I can access the values using fetch api?
I have a json data and I wanted to know how I can access the values using fetch api?

Time:11-18

I have a json data and I wanted to know how I can access the values using fetch api so that I can print it on the screen. the json data from jsonplaceholder enter image description here

. the code of that page.



import React, { useEffect, useState } from 'react';

function More() {
    const [item, setItem] = useState();
    const queryParams = new URLSearchParams(window.location.search);
    const id = queryParams.get("id");
    const fetchData = () => {
        fetch(`https://jsonplaceholder.typicode.com/todos?userId=1&&id=${id}`)
            .then((response) => response.json())
            .then((json) => {
                console.log(json)
                setItem(json)
                // console.log(item)

            });
    };

    useEffect(() => {
        fetchData();
    }, [1])

    //const id = new URLSearchParams(search).id;
    //console.log(id);
    return (
        <div>
            <h1>more information about list</h1>
            <h3>Todo id: </h3>
        </div>
    )
}
export default More;


CodePudding user response:

Please use const queryParams and const id in your code and remove const id = 1;

const App = () => {
    const [item, setItem] = React.useState({});
    // const queryParams = new URLSearchParams(window.location.search);
    // const id = queryParams.get("id");
    const id = 1;
    const fetchData = () => {
        fetch(`https://jsonplaceholder.typicode.com/todos?userId=1&id=${id}`)
            .then((response) => response.json())
            .then((json) => setItem(json[0]));
    };

    React.useEffect(() => {
        fetchData();
    }, [id])

    return (
        <div>
            <h1>more information about list</h1>
            <h3>Todo id: {item.id}</h3>
            <p>User id: {item.userId}</p>
            <p>Title: {item.title}</p>
            <p>Completed: {item.completed   ""}</p>
        </div>
    )
}

ReactDOM.render(
  <App/>,
  document.getElementById('root')
);
<script src="https://unpkg.com/[email protected]/umd/react.development.js"></script>
<script src="https://unpkg.com/[email protected]/umd/react-dom.development.js"></script>
<div id="root"></div>

CodePudding user response:

Your code perfect. Please add this code in your code.

<div>
  <h1>more information about list</h1>
  {item?.map((data, i) => (
    <div>
      <h3>Todo id: {data.id}</h3>
      <h3>Todo id: {data.title}</h3>
    </div>
  ))}
</div>
  • Related