skip to Main Content

Is it possible to retrieve the data acquired in the parent action without having to refetch them?

For example:
routes/parent.tsx
routes/parent.$id.tsx

In the parent.tsx, in action route, I get some data:

export const action: ActionFunction = async ({ request }) => {
    const data = something
    return data;
}

How to get these same data in the child route parent.$id.tsx without having to refetch them in the loader route ?

2

Answers


  1. Chosen as BEST ANSWER

    I can't get it to work, useOutletContext return undefined in child route (parent.$id.tsx).

    Here is a sample code (based on https://docs.w3cub.com/react_router/hooks/use-outlet-context)

    parent.tsx

    import { ActionFunction } from "@remix-run/node";
    import { Form, Link, Outlet, useActionData, useOutletContext } from "@remix-run/react";
    
    export const action: ActionFunction = async ({ request }) => {
        /*const formData = await request.formData();
        const search = formData.get("search") as string;
        ...*/
    
        const data = {
            Id: 123,
            Name: 'My product'
        };
    
        return data;
    }
    
    export default function Parent() {
        const data = useActionData<typeof action>();
    
        return (
            <>
                <h1>Parent</h1>
    
                <Form method="post">
                    <input type="text" name="search" id="search" placeholder="search" />
                </Form>
    
                {data ? (
                    <>
                        <Link to={`/parent/${data.Id}`}>
                            {data.Name}
                        </Link>
                    </>
                ) : null }
    
                <Outlet context={{ data }} />
            </>
        );
    }
    
    export function useData() {
        return useOutletContext();
    }
    

    parent.$id.tsx

    import { useData } from "./parent";
    
    export default function Child() {
        const { data }: any = useData();
    
        console.log(data); ==> return undefined!
    
        return (
            <h1>Child</h1>
        )
    }
    

    What is wrong in this code ?


  2. The useOutletContext hook is what you are looking for.

    Details are in the docs: https://remix.run/docs/en/main/hooks/use-outlet-context

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search