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

Finding the location of a file within a published web component

I am currently working on a webcomponent where I need to include a link tag in the head section and set the href attribute to a folder within a node module. At this stage, during the development of my component, my project structure looks like this: http ...

Connect ngx-time picker to form input in Angular

Currently, I have successfully implemented Angular material date pickers in my project, however, I am facing a challenge with integrating time pickers as it is not natively supported by Angular Material for version 8. To address this issue, I am utilizing ...

What are some top tips for setting up a solidity contract with react?

For the past 3 months, I have been delving into solidity and exploring its intricacies. However, I now find myself facing a dilemma on how to effectively link my contract with frontend technologies such as React or Next. Each developer has their unique a ...

Ways to troubleshoot and resolve the npx create-next-app issue

Every time I try to create a new app using npx create-next-app@latest --typescript, it keeps giving me this error message: npm ERR! code ENETUNREACH npm ERR! syscall connect npm ERR! errno ENETUNREACH npm ERR! request to https://registry.npmjs.org/create-n ...

Tips for reverting from Angular 7 to Angular 6

I attempted to switch from angular 7 back to angular 6 by executing the following npm commands: npm uninstall -g angular-cli npm cache clean npm install -g <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="32535c55475e53401f515e5 ...

Looking for a JavaScript (Angular) event listener to trigger when closing pages and tabs

I am looking for an event that will only work when closing a page or tab, but should not be triggered when the page is refreshed. I am aware of the "beforeunload" event, but it also gets activated on page refresh. Below is the code snippet I am currently ...

Define the format for the output file name in TypeScript

I am trying to change the filename of a TypeScript generated js file. How can I accomplish this? For instance, I currently have MyCompany.ClassA.ts The default output filename is MyCompany.ClassA.js However, I would like the output filename to be MyComp ...

Transitioning from embedded browser to system browser in a Next.js / React.JS application

I'm currently dealing with an issue on my Next.js payment page and could really use some expertise. Here's the situation at hand: My payment page has a QR code that directs users to the payment page created with Next.js. When users scan this QR ...

Issue in Ionic 2: typescript: The identifier 'EventStaffLogService' could not be located

I encountered an error after updating the app scripts. Although I've installed the latest version, I am not familiar with typescript. The code used to function properly before I executed the update. cli $ ionic serve Running 'serve:before' ...

How to Retrieve a Global Variable in an Angular Template

Is there a way to access a global variable from an Angular template? let unableToAccess = false; @Component({ selector: 'app-payment', templateUrl: './buy.component.html', styleUrls: ['./buy.component.scss'] }) export ...

What could be causing my middleware to fail in safeguarding routes?

I am currently working with next.js and attempting to implement middleware. My goal is to restrict access to certain pages, such as the profile page, if the user does not have a valid token stored in their cookies. However, I seem to be encountering an iss ...

Completing a fetch promise and sending the outcome to a function that is not awaited

I have a function that retrieves data from a Postgresql database and returns it. The expected behavior is to fetch the data using the async function getCat(), process it in const Catalogue, and then return it to a ReactJS component. catalogue.tsx: import ...

What is the proper way to validate a property name against its corresponding value?

Here is the structure of my User class: export class User { public id: number; //Basic information public email: string; public firstName: string; public lastName: string; //Permissions public canHangSocks: boolean; p ...

Utilizing TypedPropertyDescriptor to limit decorators in Typescript when using decorator factories

When it comes to restricting what a decorator can apply on, the standard method involves using a TypedPropertyDescriptor like so: export function decorator(target, key, TypedPropertyDescriptor<T extends ...>) {...} While this approach works well whe ...

Issue: Unhandled promise rejection: BraintreeError: The 'authorization' parameter is mandatory for creating a client

I'm currently working on integrating Braintree using Angular with asp.net core. However, I've encountered an issue that I can't seem to solve. I'm following this article. The version of Angular I'm using is 14, and I have replicate ...

In TypeScript, a mapped type is not allowed to define properties or methods

My challenge involves defining an interface with keys that match a specific enum key type. However, when I attempt to declare this type, I encounter the following error message: A mapped type may not declare properties or methods. Below is the code snip ...

Specific TypeScript function that exclusively accepts types such as `number|undefined` and does not simply accept `number` alone

I've been working on creating a utility class that can help me throw an exception when something may be undefined, like throwIfUndefined(array[index]).function() and throwIfUndefined(obj.key).function(). My goal is to streamline my code as using if co ...

Analyzing elements within an array using Angular 4

I have an array filled with various Objects such as: [ {"id":1,"host":"localhost","filesize":73,"fileage":"2018-01-26 09:26:40"}, {"id":2,"host":"localhost","filesize":21,"fileage":"2018-01-26 09:26:32"}, {...} ] These objects are displayed in the fol ...

When employing `queryParams` in Angular routing, the URL will automatically replace `%` with `%25`

When trying to use queryParams for navigation in Angular routing, I encountered an issue. <a routerLink='/master' [queryParams]="{query:'%US',mode:'text'}"><li (click)="search()">Search</li></a> The d ...

Encountering a 404 error when utilizing ngx-monaco-editor within an Angular application

I have been encountering an issue while attempting to utilize the editor within my Angular 8 application. Despite researching similar errors on Stack Overflow and GitHub discussions, I haven't found a solution yet. Here's how my angular.json asse ...