Home > OS >  How do I make the initial value of a useState be a value from a prop inside the component?
How do I make the initial value of a useState be a value from a prop inside the component?

Time:09-16

I'm trying to set props.title as the initial value for useState( ); in the HomeCard component and when I tried logging the card variable in the console of the OrderBody component, I keep getting undefined, what might be wrong?

NOTE: I'm using Context api here to share information from the HomeCard component to the OrderBody component, and the connection is well set.

HomeCard component:

import { useState, createContext} from 'react';
import './HomeCard.css';


//context api
export const CardContext = createContext();

function HomeCard(props){

  const [card, setCard] = useState(props.title);

  
    return(

      <CardContext.Provider value={{card}}>
            {props.children}
              
        <div className="card">
              <div className="card-body">
                <img src={props.img} width={250} height={220} className="card-img"/>
                <h2 className="card-title">{props.title}</h2>
                <p className="card-description">{props.description}</p>
              </div>
              <button className="card-btn">Add to Cart</button>
        </div>

        </CardContext.Provider>
    )
}

export default HomeCard;

OrderBody component:

import { useContext } from "react";//importing useContext
import { CardContext } from "../../HomeFolder/HomeCardFolder/HomeCardFolder/HomeCard";//importing card context


import './OrderBody.css'

function OrderBody(){

  const {card} = useContext(CardContext);
  console.log(card)


  return (
    <div className="OrderBodyContainer">
        <h6>order list</h6>
    </div>
  )
}

export default OrderBody;

CodePudding user response:

The initial state is running before the props contents have been fetched. The solution is to simply use the setter function of the state:

function HomeCard(props){

  const [card, setCard] = useState();
  setCard(props.title)

Now, whenever the title changes or updates, the state will be set accordingly.

CodePudding user response:

set const [card, setCard] = useState(props.title); to const [card, setCard] = useState(props.title || "");

and add useEffect to rerender and update state when the props.title changes

useEffect(()=>{
  props.title && setCard(props.title)
},[props.title])

  • Related