Currently, I am working on an app that integrates ChatGPT to fetch recipes based on user-input ingredients. After receiving the JSON response from CGPT, I aim to display a Recipe "Card" component. However, I encounter an error titled above when attempting to pass the recipe state to the Recipe component. It seems like {recipe: null} is being returned because it is not set until after the user submits their chosen ingredients. How can I conditionally pass down the recipe state once it is ready? See the code snippet below:
This is the component responsible for handling all the search logic
'use client'
import { useState } from "react";
import Recipe from './components/Recipe'
const Recipes = () => {
const [ingredients, setIngredients] = useState('')
const [recipe, setRecipe ] = useState(null)
const [ingredientList, setIngredientList] = useState('')
const [isLoading, setIsLoading] = useState(1)
const getRecipe = async function getRecipe(e: React.FormEvent<HTMLFormElement>){
e.preventDefault()
setIngredientList(ingredients)
setIsLoading(2)
const response = await fetch('/api/recipes', {
method: 'POST',
body: ingredients
})
const recipe = await response.json()
if (recipe){
setRecipe(recipe)
setIngredients('')
console.log(recipe)
}
}
return (
<>
<div>
<div>
<form onSubmit={getRecipe} >
<input className=" bg-blue-600 text-black" type='text' placeholder='add your ingredients' value={ingredients} onChange={(e) => {setIngredients(e.target.value)}}/>
<button type="submit">get recipes</button>
</form>
</div>
<Recipe recipe={recipe}/>
</div>
</>
);
};
export default Recipes;
Recipe "Card" Component
import React from 'react'
type Recipe = {
title: string,
servings: string,
ingredients: string[]
instructions: string[]
}
const RecipeComponent = (props: Recipe) => {
return (
<div className='p-10'>
<div>
<h1>Recipe Name</h1>
{props.title}
</div>
<div>
<h1>Instructions</h1>
<ul>
{props.instructions?.map((instruction: string) => <li>{instruction}</li>)}
</ul>
</div>
</div>
)
}
export default RecipeComponent
I attempted to move the Recipe type to the search logic component but saw no changes. I believe the issue lies in passing down something that is not available yet. Perhaps, I could conditionally render the entire Recipe Card component so it only appears when there is definitely a recipe. As a newcomer to Typescript, any guidance would be greatly appreciated!