0

I am creating a React app that uses Fetch to pull a API using SQLite, however for some reason it shows in console length: 3, and Array[0] only. I cannot pull from data just id 1 for example.

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

export default () => {
    const [brands, setBrands] = useState(null);

    useEffect(() => {
        fetch("/api/brands")
            .then((response) => response.json())
            .then((data) => console.log(data))
            .then((data) => {
                setBrands(data);
            });
    }, []);
    return (
        <>
            {brands ? (
                <>
                    <h1>Brands</h1>
                    <ul>
                        {brands.map((brand) => (
                            <li key={brand.id}>{brand.name}</li>
                        ))}
                    </ul>
                </>
            ) : (
                <div>Loading...</div>
            )}
        </>
    );
};

Example Screen shot of Array being 0

How would I be able to pull from this id 1 for example? at the moment only all the brands show when I remove the console log and show as I pasted in the screen shot above in console.

3
  • Are you asking for a way to find an array entry by id? console.log(brands.find(brand => brand.id === 1)); Commented Nov 1, 2022 at 9:48
  • If not, please share your console log code and define what you expect. Commented Nov 1, 2022 at 9:49
  • @RoySchut I am looking to not in the console but within the page show only 1 item from brands. Only console code I have is to log what shows up in the screen shot I provided (Hid sensitive details). I want where <ul> {brands.map((brand) => ( <li key={brand.id}>{brand.name}</li> ))} </ul> to show only brand name with id of 1. Commented Nov 1, 2022 at 12:36

2 Answers 2

1

If I understand your question then you want to display only one item from an array of items fetched via an API.

Its not clear where or how you determine which item you want. Is it a component prop?

My first suggestion is simply implement an API endpoint that returns only one item based on a parameter eg.

fetch(`/api/brands/${some_id_for_the_record_i_want}`)

If you can't modify the API then you can use filter/find to limit the items you want BEFORE setting state eg. - this example uses find which returns a single match or undefined.

useEffect(() => {
    fetch("/api/brands")
        .then((response) => response.json())
        .then((data) => {
            setBrands(data.find(f => f.id === 1));
        });
}, []);

Worst case just do filter/find in the JSX eg. - this example uses filter which returns an array of matches or an empty array.

return (
    <>
        {(() => {

            if(brands) {

                const filteredBrands = brands.filter(f => f.name === 'somename');
                return (
                    <>
                        <h1>Brands</h1>
                        <ul>
                            {filteredBrands.map((brand) => (
                                <li key={brand.id}>{brand.name}</li>
                            ))}
                        </ul>
                    </>
                )

                // Want a single match?
                // const singleBrand = brands.find(f => f.id=== 1);
                //return (
                //    <>
                //        <h1>Brands</h1>
                //        <div>{singleBrand?.name}<div>
                //    </>
                //)
            } else {
                return <div>Loading...</div>
            }
            
        })()}
    </>
);
Sign up to request clarification or add additional context in comments.

Comments

0

From what I understand, you want to show data for a single id (i.e. brand) instead of for all brands. I would do it like this.

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

export default () => {
    const [allBrands, setAllBrands] = useState(null);
    const [specificBrand, setSpecificBrand] = useState(null);

    useEffect(() => {
        fetch("/api/brands")
            .then((response) => response.json())
            .then((data) => {
                setAllBrands(data);
            });
    }, []);

    useEffect(() => {
        if(allBrands.length){
            setSpecificBrand(allBrands.find(brand => brand .id === 1);
        }
    }, [allBrands]);

    return (
        <>
            {specificBrand? (
                <>
                    <h1>Brands</h1>
                    <ul>
                        <li key={specificBrand.id}>{specificBrand.name}</li>
                    </ul>
                </>
            ) : (
                <div>Loading...</div>
            )}
        </>
    );
};

The API endpoint suggestion also seems like a good idea.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.