Home > Mobile >  display fetched data from bearer token api in reactjs
display fetched data from bearer token api in reactjs

Time:11-17

im trying to display the fetched data from a bearer token API but I couldn't

I could see the data in the console

here is my code:

  const [products, setProdcts] = useState([]);      
fetch("https://RANDOMAPI.com/api/products", {
        method: "GET",
        headers: {
          Authorization: `Bearer ${accessToken}`,
          "Content-Type": "application/json",
        },
        mode: "cors",
        cache: "default",
      })
        .then((response) => response.json())
        .then((json) => console.log(json))
        .catch((error) => console.log(error));
      console.log("response");
    
    
    {products?.length > 0 ? (
            <div className="container">
              {products.map((product) => (
                <div className="product">
                  <p>{product. Name}</p>
                </div>
              ))}
            </div>
          ) : (
            <div className="empty">
              <h2>No products found</h2>
            </div>
          )}

Im not sure if there is any other way to display the data other than mapping

please tell me if im doing something wrong?

CodePudding user response:

The data is only being logged to the console because this is what you're doing with the data:

.then((json) => console.log(json))

Calling console.log logs the data to the console. It does not have any effect on the products state value.

If you're looking to update that state value with the fetched data, update the state value:

.then((json) => setProdcts(json))

This will trigger a re-render of the component with the newly updated state data.

  • Related