skip to Main Content

I want to render component based on props. These props will also have to pass with useLazyQuery() hook to generate dynamic URL and view data. If I pass only credentials, the generated data is fine. But when I am trying to add props with it, always generates error.

What to do ? Please help.

My Base Query Slice :

import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'

const baseQuery = fetchBaseQuery({
    baseUrl: 'http://localhost:8080',
    credentials: 'include',
    prepareHeaders: (headers, { getState }) => {
        const token = getState().auth.accessToken
        if (token) {
            headers.set('authorization', `Bearer~${token}`)
        }
        return headers
    }
})
export const apiSlice = createApi({
    baseQuery,
    endpoints: builder => ({})
})

My Injected Query Slice :

import { apiSlice } from "../../app/api/apiSlice";

//Dynamic URL based on props
const leaveApplViewUrlGen = nature => {
    switch (nature) {
        case 'apr': return '/hr/leave/application/apr'
        case 'can': return '/hr/leave/application/can'
    }
}
const leaveApplViewUrlSelf = nature => {
    switch (nature) {
        case 'apr': return '/hr/leave/application/self/apr'
        case 'can': return '/hr/leave/application/self/can'
    }
}

export const leaveApiSlice = apiSlice.injectEndpoints({
    tagTypes: ['Appl'],
    endpoints: builder => ({
        leaveApplView: builder.query({
    // Problem generating through here
    // I want to generate dynamic URL based on props value
            query: ({credentials, self, nature}) => ({
                url: self
                    ? leaveApplViewUrlSelf(nature)
                    : leaveApplViewUrlGen(nature),
                method: 'POST',
                body: { ...credentials }
            }),
        }),
    })
})

export const {
    useLazyLeaveApplViewQuery
} = leaveApiSlice

My Complnent:

    import { useEffect, useState } from "react"
    import Select from 'react-select'
    import {
        useLazyLeaveApplViewQuery
    } from "../../../features/hr/leaveApiSlice"
    
        // Component loading based on props
    const LeaveAppl = ({ self, nature }) => {
    
        const projectCodes = [
            { value: '84', label: '84' }
        ]
        const reportYears = [
            { value: '2022', label: '2022' }
        ]
        const reportMonths = [
            { value: '03', label: 'MAR' }
        ]
    
        const [projectCode, setProjectCode] = useState(projectCodes[0].value)
        const [reportYear, setReportYear] = useState(reportYears[0].value)
        const [reportMonth, setReportMonth] = useState(reportMonths[0].value)
        const employeeCode = ''
    
        const [applTrigger, applData] = useLazyLeaveApplViewQuery()
    
        useEffect(() => {
            setProjectCode(projectCodes[0].value)
            setReportYear(reportYears[0].value)
            setReportMonth(reportMonths[0].value)
        }, [self, nature])
    
        const refreshLeave = async (e) => {
            e.preventDefault()
    
            const applCredentials = self
                ? { projectCode, reportYear, reportMonth }
                : { projectCode, reportYear, reportMonth, employeeCode }
    
            try {
        // Problem generating from here
        // I want to generate dynamic URL based on props value
                await applTrigger(
                    { applCredentials, self, nature }).unwrap()
                if (applData.isSuccess && applData.data) {
                    console.log(applData.data)
                }
            } catch (err) {
                if (!err?.originalStatus) {
                    console.err('Processing Error!');
                }
            }
        }
    
        return (
            <section className='leave-appl'>
                <form>
                    <Select options={projectCodes}
                        onChange={e => setProjectCode(e.value)}
                    />
                    <Select options={reportYears}
                        onChange={e => setReportYear(e.value)}
                    />
                    <Select options={reportMonths}
                        onChange={e => setReportMonth(e.value)}
                    />
                    <button type='button' onClick={refreshLeave}
                    >Refresh</button>
                </form>
            </section>
        )
    }

export default LeaveAppl

2

Answers


  1. Chosen as BEST ANSWER

    The problem is solved. Pass it like this:-

    await applTrigger({ ...credentials, self, nature }).unwrap()
    

    Thanks.


  2. You pass them in as args in your function call, exactly as you are already doing:

    applTrigger({ applCredentials, self, nature })
    

    This is correct code. As you are not sharing the error message, it’s not really possible to give any feedback on that.

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