Randy_Johnson's avatar

ReactJS Refresh a child comp from another child comp

I have my components set up like so, and in product it adds to the DB, the problem is is getting the Cart to refresh to show this. When I started the product (my first reactjs) I passed it over using Context with bothing to add anything to the data. But once I needed to add it to the db for persistence I deleted the context.

Is it right to set up the project in such a way that in the beginning to pull db, save it into context and work with it from there whilst updating the db for persistence? Or is there an easy way I can just refresh the Cart component from the product component without having to use callback, or usecontext?

┌────────────────────────────────┐
│Page                            │
│                                │
├┬──────────────┐  ┌────────────┬┤
││Products      │  │ Cart       ││
││              │  │            ││
│┼┬────────────┬┤  │            ││
│┼│product     ││  │            ││
│┼│            ││  │            ││
│┼┼────────────┼│  │            ││
│┼┼┼┼┼┼┼┼┼┼┼┼┼┼┼│  ├────────────┼│
└───────────────┴──┴─────────────┘

0 likes
3 replies
Sinnbeck's avatar

If you are persisting it in the database also, why not just pass it down to the page (with Inertia::render()) ? If you need to get it in the cart you can easily grab it with usePage()

Inside the Cart component (or any component really)

const {cart} = usePage().props

If the cart is on every single page in the app, you can even share it with all components by using https://inertiajs.com/shared-data

Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

Maybe to practice inertia/react, make a test page where you pass down some sort of data. It could be something from cache or session. Then make a post request to update it and redirect back. Now see if your data automatically updates on the page. It should :)

For instance on some pages I have the option to auto reload data (like horizon). If you enable it, it is stored to session. I have this method to update it

public function store(Request $request)
    {
        $value = $request->get('autoReload');
        $request->session()->put('autoReload', $value);

        return redirect()->back();
    }

and I have a component to trigger it on and off, I can add to pages where needed

router.post(
    route('autoreload.store'),
    {autoReload: !autoReload},
    {
        only: ['autoReload'],
        replace: true,
    }
)
1 like

Please or to participate in this conversation.