1

I'm trying to learn how to use Loaders in React-router-dom and can't get two parameters working.

export const loadConvoMsg = ({conversationId, courseId}) => async () => {
    console.log('convoIDLoad', conversationId)
    console.log('courseIdLoad', courseId)
    if (conversationId) {
        console.log('conversationId type', typeof conversationId)
        const response = await fetch(`http://127.0.0.1:8000/chat/conversation/${conversationId}`);
        // const response = await fetch(`http://127.0.0.1:8000/chat/conversation/1`);
        console.log('hello')
        const data = await response.json();
        console.log(data)
        return data;
    }
    else if (courseId) {
        console.log('courseId in loader', courseId)
        console.log('conversationId in loader', conversationId)
        const response = await fetch(`http://127.0.0.1:8000/chat/course/${courseId}`);
        // const response = await fetch(`http://127.0.0.1:8000/chat/course/1`);
        const data = await response.json();
        return data;
    }
    else {
        return null
    }

From Loader.js

I tried a combination of calls in sidebar.js which imports loadConvoMsg from Loader.js

const convos = useLoaderData(loadConvoMsg({ courseId: 1, conversationId: '' })()); cons convos = useLoaderData(loadConvoMsg, {courseid: 1, conversationId: ''})

then in App.js

        <Route path="chat" element={<Chat />} loader={loadConvoMsg} />
        <Route path='/chat/conversation/:pageId' element={<Chat />} loader={loadConvoMsg} />

where sidebar is in chat.js

const convos = useLoaderData(loadConvoMsg({ courseId: 1, conversationId: '' })());

result: console.log(convos) => a function of async

Other calls did the same or gave me null because the parameters were undefined.

There are no issues in the backend as I am able to get/post just fine.

bluelemur
  • 33
  • 4

1 Answers1

0

It seems you have a misunderstanding of how the new react-router v6 loader works.

The loader function is intended to facilitate data loading process and reduce boilerplate code. It must be asynchronous itself (not returning another async function as in your code). Also, the loader function has two parameters, request and params.

Here's an example of how to use it properly:

export const loadConvoMsg => async ({params}) => {
    console.log('convoIDLoad', params.conversationId)
    console.log('courseIdLoad', params.courseId)
    ...
    return data;
}

Next, you can access loader data by using the useLoaderData() hook without passing any data to the hook. This should resolve your problem.

Souhaib
  • 119
  • 1
  • 6