The 'roleName' property is not found within the 'never' data type

// ** React Component and Library Imports
import { useEffect, useState } from 'react'
import Box, { BoxProps } from '@mui/material/Box'
import Button from '@mui/material/Button'
import Drawer from '@mui/material/Drawer'
import FormControl from '@mui/material/FormControl'
import FormHelperText from '@mui/material/FormHelperText'
import IconButton from '@mui/material/IconButton'
import InputLabel from '@mui/material/InputLabel'
import MenuItem from '@mui/material/MenuItem'
import Select from '@mui/material/Select'
import { styled } from '@mui/material/styles'
import TextField from '@mui/material/TextField'
import Typography from '@mui/material/Typography'

// ** Third Party Imports
import { yupResolver } from '@hookform/resolvers/yup'
import { Controller, useForm } from 'react-hook-form'
import * as yup from 'yup'

// ** Icon Imports
import Icon from 'src/@core/components/icon'

// ** Store and Actions Imports
import { useDispatch, useSelector } from 'react-redux'
import { addUser } from 'src/store/apps/user'
import { AppDispatch, RootState } from 'src/store'
import { fetchDesignation } from 'src/store/apps/designation'
import { fetchRole } from 'src/store/apps/role'

interface SidebarAddUserType {
    open: boolean
    toggle: () => void
}

interface UserData {
    firstName: string
    middleName: string
    lastName: string
    loginId: string
    emailId: string
    mobileNumber: string
}

const showErrors = (field: string, valueLen: number, min: number) => {
    if (valueLen === 0) {
        return `${field} field is required`
    } else if (valueLen > 0 && valueLen < min) {
        return `${field} must be at least ${min} characters`
    } else {
        return ''
    }
}

const Header = styled(Box)<BoxProps>(({ theme }) => ({
    display: 'flex',
    alignItems: 'center',
    padding: theme.spacing(3, 4),
    justifyContent: 'space-between',
    backgroundColor: theme.palette.background.default
}))

const schema = yup.object().shape({
    emailId: yup.string().email().required(),
    mobileNumber: yup
        .string()
        .typeError('Mobile Number field is required')
        .required(),
    firstName: yup
        .string()
        .required(),
    middleName: yup.string(),
    lastName: yup
        .string()
        .required(),
    loginId: yup
        .string()
        .required(),
})

const defaultValues = {
    firstName: '',
    middleName: '',
    lastName: '',
    loginId: '',
    emailId: '',
    mobileNumber: ''
}

const SidebarAddUser = (props: SidebarAddUserType) => {
    const { open, toggle } = props

    // ** State
    const [plan, setPlan] = useState<string>('basic')
    const [roleId, setRoleId] = useState<string>('')
    const [reportsTo, setReporterTo] = useState<string>('')
    const [departmentId, setDepartmentId] = useState<string>('')
    const [designationId, setDesignationId] = useState<string>('')

    const dispatch = useDispatch<AppDispatch>()
    const store = useSelector((state: RootState) => state.role)
    const designations = useSelector((state: RootState) => state.designation)

    useEffect(() => {
        dispatch(fetchRole({}))
        dispatch(fetchDesignation({}))
    }, [])

    const { reset, control, handleSubmit, formState: { errors } } = useForm({
        defaultValues,
        mode: 'onChange',
        resolver: yupResolver(schema)
    })

    const onSubmit = (data: UserData) => {
        console.log({ ...data, roleId, reportsTo, departmentId, designationId })
        dispatch(addUser({ ...data, roleId, reportsTo, departmentId, designationId }))
        toggle()
        reset()
    }

    const handleClose = () => {
        setPlan('basic')
        toggle()
        reset()
    }

    return (
        <Drawer
          open={open}
          anchor='right'
          variant='temporary'
          onClose={handleClose}
          ModalProps={{ keepMounted: true }}
          sx={{ '& .MuiDrawer-paper': { width: { xs: 600, sm: 450 } } }}
        >
            <Header>
                <Typography variant='h6'>Add User</Typography>
                <IconButton size='small' onClick={handleClose} sx={{ color: 'text.primary' }}>
                    <Icon icon='mdi:close' fontSize={20} />
                </IconButton>
            </Header>
            <Box sx={{ p: 5 }}>
                <form onSubmit={handleSubmit(onSubmit)}>
                  {/* Form Fields */}
                </form>
            </Box>
        </Drawer>
    )
}

export default SidebarAddUser

The "id" and "role name" in red lines are dynamic values fetched from an API. You would specify the interface for this API result data at the point of setting the corresponding state variables.

For instance, in the `fetchRole` function from 'src/store/apps/role', you can see how the API response sets the `state.role` and `state.allRole` values. This is where you would define the structure of the returned data.

In your case, since `state.role` is being set to `action.payload.data`, ensure that the shape of `action.payload.data` matches the expected format of roles data with properties like "id", "roleName", etc.

Additionally, make sure you have defined the RootState type correctly in the file where it is used by importing it from `'src/store'`:

export type RootState = ReturnType<typeof store.getState>

With these implementations, you can properly handle and define the interfaces for the dynamic data coming from the API within your components and redux actions.

Answer №1

When declaring an empty array in TypeScript without specifying a type, the inferred type of the array items will be never. To avoid this, you should assign a type to your array like so:

interface Role {
  id: string;
  roleName: string;
}

export const appRolesSlice = createSlice({
  ...
  initialState: {
    role: [] as Array<Role>,
    allRole: []
  },
  ...
})

It's important to also specify a type for the allRole property.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error message: "Netlify CLI encountered an issue while deploying Next.js runtime - unable to locate

Being completely transparent, I am posting this issue here because the Netlify forum restricts me from adding more than one media link to an issue, and I wanted to provide additional details. You can find my original post here. The Issue: When deploying ...

What is the process of organizing information with http in Angular 2?

Currently, I am working through a heroes tutorial and have made progress with the code so far. You can view the code <a href="https://plnkr.co/edit/YHzyzm6ZXt4ESr76mNuB?preview" rel="nofollow noreferrer">here</a>. My next goal is to implement ...

The data structure of '(string | undefined)[]' cannot be matched with type '[string | undefined]'

I've been working on a TypeScript project and I've encountered the ts(2322) error as my current challenge. Here's a snippet of my code: import { BASE_URL, AIRTABLE_BASE_ID, AIRTABLE_TABLE_STUDENT, AIRTABLE_TABLE_CLASSES, API_KEY, ...

I was surprised by how Await behaved in if-else statements, it was not what

let metadata = []; allNFTs.map(async (e) => { if (e.metadata) { metadata.push(JSON.parse(e.metadata).attributes); } else { let config = { method: "get", url: `http://localhost:3000/api/fetch ...

Bring in SASS variables to enhance Material UI theme in NextJS

Within my project, I currently have the following two files: materialTheme.ts import { createMuiTheme, Theme } from "@material-ui/core/styles"; const theme: Theme = createMuiTheme({ palette: { primary: { main: "#209dd2", contras ...

The cascading effect is visible on an inactive button contained within an interactive card

I've encountered an issue where I've set the button property clickable="false" inside a card that has properties clickable=true and android:foreground="?android:attr/selectableItemBackground". However, when I click on the card, the button also di ...

Update the input value with the selected option from the dropdown menu in Angular

How can I dynamically set the value of an input field based on the selection from a dropdown menu in Angular using Reactive Forms? Below is my HTML code: <nb-card> <nb-card-header> Services </nb-card-header> <nb-card-body&g ...

What is the solution to the error message "Error: Missing 'key' prop for element in array react/jsx-key" when using react-icons with mapping in React?

After trying multiple methods to dynamically display icons, I finally found one that works in my case: <div style={{display: "flex", flexDirection: "row"}}> {logo?.map((logos, index )=> {return ( <React.Fragment key={ind ...

Testing Angular applications using Karma

After utilizing the yo angular 1 generator, it generated a landing page and some tests. However, I am facing an issue when trying to compile the code in VS as I receive an error stating that "module('fountainFooter');" is undefined. /// <refe ...

Modifying the state object in ReactJS: A step-by-step guide on updating values

Below my query and explanation, you will find all the code. I am currently attempting to update the state in a grandparent class. This is necessary due to file-related reasons, and I am using Material-UI for text boxes. Additionally, I am implementing Red ...

Next.js Version 13 - Unable to find solution for 'supports-color' conflict

Currently in the midst of developing a Next.js 13 app (with TypeScript) and utilizing the Sendgrid npm package. An ongoing issue keeps popping up: Module not found: Can't resolve 'supports-color' in '.../node_modules/debug/src' ...

Unable to replicate the function

When attempting to replicate a function, I encountered a RootNavigator error Error in duplicate function implementation.ts(2393) I tried adding an export at the top but it didn't resolve the issue export {} Link to React Navigation options documen ...

What is the best way to resolve the unusual resolution issue that arises when switching from Next.js 12 to 13

Previously, I created a website using nextjs 12 and now I am looking to rebuild it entirely with nextjs 13. During the upgrade process, I encountered some strange issues. For example, the index page functions properly on my local build but not on Vercel. ...

Struggling to align the navbar and logo in the center using tailwind CSS

I utilized tailwind css to style my navbar, which resulted in all elements being displayed inline. However, I am looking to center all the content instead. Can someone assist me in modifying the code to achieve a centered header using tailwind css? Header ...

What is the best way to utilize data from the previous page following a change in the URL using router.push()?

While using the App Router in nextjs 13, a /quiz page is implemented. Once a user completes the quiz, their results are stored in the database and they are then directed to the /results page. The data stored during the quiz is used on the results page. Cu ...

Increase the placeholder's line height and font size for the InputBase component in Material UI

Hello, I am new to material UI and currently using it for my website development. I am trying to customize the placeholder of the inputbase in material ui by increasing their lineHeight and fontSize. However, I am having trouble accessing the placeholder A ...

The functionality of the Material UI Icon is not meeting expectations

I have been exploring Material UI and came across an interesting discrepancy. The documentation suggests using the following code snippet: import Icon from "@material-ui/core/Icon"; ... <Button variant="contained" color="primary" className={class ...

Material-UI: The call stack has exceeded the maximum range, causing an Uncaught RangeError

I am currently utilizing the Dialog and Select components offered by Material-UI in conjunction with React. Here is a quick example: import React from 'react'; import { Dialog, MenuItem, Select } from '@material-ui/core'; class Examp ...

A more effective way to obtain exclusive information through Next.js

Whenever a user accesses a specific page (e.g. /post/1), I aim to retrieve the data related to post 1. To achieve this, I extract the URL pathname using window.location.pathname (such as /post/1), eliminate the initial characters (/post/) using substring, ...

Creating Angular models for complex nested JSON structures

I'm a beginner with Angular and I'm dealing with nested API responses from a Strapi application. I've set up a model using interfaces, but I'm having trouble accessing attributes from the product model when trying to access product data ...