0
function Route()
{
    const [Items, setItems] = useState([]);
    const [status, setQuotestatus] = useState(true);
    const [quotation, setQuotation] = useState({quoteNo: "", type: "Project", quoteDate: "", validity: "", total: 0});
const callback = useCallback((Items,quotation) =>
    {
        setItems(Items);
        setQuotation(quotation);
        console.log(status)
        setQuotestatus(!status);
        console.log(quotation,status);
    }, [],);
 if(status)
    {
        return (<Quote allItems={Items} quote={quotation} parentCallback={callback} />);
    }
    else
    {
        return (<Documents Items={Items} quote={quotation} parentCallback={callback} />);
    }
}

export default Route;

I'm using useCallBack to switch and pass parameters between 2 child components that have same parent component <Route />. The default case and first switching is working on using use Callback, but when I tried to call this same useCallback from the next components it is calling the hook but component is not shifting to next. That is I'm able to go to <Quote />, then able move to <Documents />. But unable to move back to <Quote /> from <Documents />

Button on <Quote />

    <button type="button" className="btn btn-primary" onClick={(e) => {e.preventDefault(); parentCallback(storedItems, {quoteNo: quoteNo, type: type, quoteDate: quoteDate, validity: validity, total: total})}} >
Preview
</button>

Button on <Documents />

<div className="col">
     <button type="button" className="btn btn-primary" onClick={(e) => {e.preventDefault(); parentCallback(storedItems, {quoteNo: quote.quoteNo, type: quote.type, quoteDate: quote.quoteDate, validity: quote.validity, total: quote.total})}} >Back</button>
</div>
Ameen NA
  • 39
  • 1
  • 1
  • 5

2 Answers2

0

Because you use status in useCallback but you don't pass it into dependencies. So status always is initial value.

You should using setState callback in this case:

const callback = useCallback((Items,quotation) =>
    {
        setItems(Items);
        setQuotation(quotation);
        setQuotestatus(preStatus => !preStatus );
    }, [],);

And you should put console.log into useEffect because the state only has new value when component re-render

useEffect(() => {
  console.log(quotation,status);
}, [quotation, status])
Viet
  • 12,133
  • 2
  • 15
  • 21
0

Instead of calling setState inside callback use a external function to change state

    const [Items, setItems] = useState([]);
    const [status, setQuotestatus] = useState(true);
    const [quotation, setQuotation] = useState({quoteNo: "", type: "Project", quoteDate: "", validity: "", total: 0});

    function preState(){
        setQuotestatus(!status);
    }

    const callback = useCallback((Items,quotation) =>
    {
        setItems(Items);
        setQuotation(quotation);
        preState();
    }, [Items, quotation],);
Ameen NA
  • 39
  • 1
  • 1
  • 5