The data structure '{ recipe: null; }' cannot be matched with type 'IntrinsicAttributes & Recipe'

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!

Answer №1

It is accurate to say that initially, the

const [recipe, setRecipe ] = useState(null)
sets the recipe as null when it first goes through rendering, which leads to a failure. There appears to be code in place to handle this situation but it is currently commented out

      {/* <div>
        {isLoading===2 && !recipe ? "loading" : recipe}
      </div> */}

To address this issue, you could modify it to display the component or include a check before rendering the component:

return (
// ...
      <div>
        {isLoading===2 && !recipe ? "loading" : <Recipe recipe={recipe}/>} // solution 1
      </div>

      {recipe && <Recipe recipe={recipe}/>} // solution 2
// ...
)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Assigning a custom class to the cdk-overlay-pane within a mat-select component is restricted to Angular Material version 10.2.7

I attempted the code below, but it only works for angular material 11. My requirement is to use only angular material 10. providers: [ { provide: MAT_SELECT_CONFIG, useValue: { overlayPanelClass: 'customClass' } } ] There a ...

How can I fix the ReferenceError that says ToolBar is not defined?

My journey with a new Next.js project began around three days ago. After updating everything, I proceeded to include the following dependencies: yarn add @material-ui/core yarn add @mui/icons-material yarn add @mui/material This is the code snippet that r ...

Encountering a connection error when trying to access a Google spreadsheet within a Next.js application

I am currently exploring Next.js and attempting to utilize Google Sheets as a database for my project. Although my application is functioning correctly, there is still an error message displaying that says "not forgot to setup environment variable". I have ...

Sending a `refresh` to a Context

I'm struggling to pass a refetch function from a useQuery() hook into a context in order to call it within the context. I've been facing issues with type mismatches, and sometimes the app crashes with an error saying that refetch() is not a funct ...

Ways to verify if an item is an Express object?

Currently, I am utilizing typescript to verify whether an app returned by the Express() function is indeed an instance of Express. This is how I am attempting to accomplish this: import Express from "express" const app = Express() console.log( ...

What materials are required in order to receive messages and information through my Contact page?

Currently, I am pondering the optimal method for gathering information from my Contact page. I have already created a form; however, I'm unsure how to send the gathered data to myself since I am relatively new to Web development. Angular is the framew ...

What is the method used by React or Next to prevent the <a> tag from refreshing the page while still loading content?

I'm currently diving into the world of NextJS and utilizing the Link component from the 'next/link' package. One thing that has been puzzling me is how the <Link> component ultimately renders an <a> tag with a href='/tosomew ...

Can a reducer be molded in ngrx without utilizing the createReducer function?

While analyzing an existing codebase, I came across a reducer function called reviewReducer that was created without using the syntax of the createReducer function. The reviewReducer function in the code snippet below behaves like a typical reducer - it t ...

Troubleshooting Problem with Next.js 13 Integration, Supabase, and Server Actions in layout.tsx

I'm currently developing a Next.js 13 application and experimenting with managing user authentication through Supabase. I've encountered some challenges when attempting to verify if a user is logged in using an asynchronous function within my lay ...

What is the reasoning behind leaving out wwwroot from tsconfig?

Currently, I am working on a TypeScript project using an ASP.NET 5 template in VS.NET 2015. In the scripts/tsconfig.json file that I added, there is a default exclude section which includes: "exclude": [ "node_modules", "wwwroot" ] However, a ...

I am encountering an issue where the object I am sending with Next.js is appearing as undefined on the receiving page

When transferring data from my question screen to a result screen, I am using an object called footprintsData. Here is the code snippet for sending the data: const footprintsData = { carFootprint: roundedCarFootprint, electricityFootprint: roundedElect ...

Troubleshooting a connection issue between Laravel and Next.js when calling axios

My current setup involves using Laravel for the backend and NextJs for the frontend. When I attempt to submit the form, I encounter an issue. The server responds with the following error message: error I have verified that the csrf token is correctly obt ...

Utilizing TypeORM in a Node.js Project

Recently, I was exploring different ORM options for my server application and came across TypeORM. I'm curious to know the best approach to organize a small project using it. While browsing through the official documentation, I found a repository that ...

Tips on adding an image using Reactjs

I am currently working in Reactjs with the Next.js framework. I am attempting to upload images using Axios (POST method API) and will be utilizing an "api in PHP". Could someone please guide me on how to achieve this? I have tried the code below, but it&ap ...

Implementing global user authentication state with Zustand in Next.js version 13.4.9

I'm grappling with incorporating zustand into my Next.js 13.4.9 app, specifically for managing global authentication state. Below is the code snippet I have in my application: zustand store: // /src/store/AuthStore.ts import { create } from 'zu ...

Is it possible to efficiently structure intricate JSON data onto interfaces in TypeScript with the incorporation of observables?

I am currently working on creating a simple web news reader that relies heavily on the Google News API (). I have set up all the necessary services, models, etc. However, I am having difficulty mapping the data onto specific interfaces. The Google API retu ...

Determine the generic types of callback in TypeScript based on the argument provided

There are numerous Stack Overflow questions that share a similar title, but it seems none of them address this particular inquiry. I'm in the process of developing a wrapper for an express RequestHandler that can catch errors in asynchronous handlers ...

Setting up grunt-ts to function seamlessly with LiveReload

I am currently experimenting with using TypeScript within a Yeoman and Grunt setup. I've been utilizing a Grunt plugin called grunt-ts to compile my TypeScript files, and while the compilation process is smooth, I'm encountering issues with live ...

Maintaining search filters across pages in Angular 2 using URL parameters

I am attempting to store certain filters in the URL for my application, so that they can be reapplied when the page is reloaded. I am encountering challenges with Dates (using moment), nullable properties, and special characters (/). When I pass values to ...

NPM installation stalls only when attempting to install the specific package, ts-jest

https://i.stack.imgur.com/Cvon1.png I've encountered an issue while trying to set up ts-jest in a new project. Here's what I've tried: $ mkdir test && cd test $ npm init -y $ npm install ts-jest Despite being able to install other ...