Search code examples
typescriptapireact-tsx

accessing and displaying arrays of objects via api with react.ts


i am trying to display list of steps/ingredients from the recipe api with react.ts but i am unsure how to define the type of nested array of objects.

i am able to access the title, image and summary but not the steps in analizedInstructions.

export function RecipeDetails() {
    const initialRecipeState = {
        title: '',
        analizedInstructions: [{
            steps: [{
                name: ''
            }]
        }],
        image: '',
        summary: ''
        
    }

    const { id } = useParams();
    const [data, setData] = useState<RecipeData>(initialRecipeState);

    useEffect( () => {
        const getData = async() => {
            const newData = await fetchData(`https://api.spoonacular.com/recipes/${id}/information?apiKey=key&includeNutrition=false`)
            setData(newData)
        }
        getData();
        console.log(data.analizedInstructions)
    },[])

this is my types file

export type RecipeData = {
    title: string,
    analizedInstructions: Steps,
    image: string,
    summary: string
}

export type Steps = {
    name: Name
}
export type Name = {
    name: string
}

and this is the data i get from the api im tying to access api data

i tried to find a solution via stackoverflow but didnt find quite what i was looking for.


Solution

  • export type RecipeData = {
        title: string,
        analizedInstructions: Instruction[],
        image: string,
        summary: string
    }
    
    export type Instruction = {
       steps: Step[]
    }
    
    export type Step = {
        name: string
    }