Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

i cannot set the type of state in typescript

I’m writing code for server error handling using typescript in react(version 6).
But i got the error from useLocation and state.
useLocation got error which message is "Expected 0 type arguments, but got 1.ts(2558)" So if i erase then the error disappeared but still state have errors like "Object is of type ‘unknown’.ts(2571) "

enter image description here

import { Button, Container, Divider, Paper, Typography } from "@mui/material"; 

import { useHistory, useLocation } from "react-router";

export default function ServerError() {
    const history = useHistory();
    const { state } = useLocation<any>();

    return (
        <Container component={Paper}>
            {state?.error ? (
                <>
                    <Typography variant='h3' color='error' gutterBottom>{state.error.title}</Typography>
                    <Divider />
                    <Typography>{state.error.detail || 'Internal server error'}</Typography>
                </>
            ) : (
                <Typography variant='h5' gutterBottom>Server Error</Typography>
            )}
            <Button onClick={() => history.push('/catalog')}>Go back to the store</Button>
        </Container>
    )
} 

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

It looks like the type of state is unknown in the useLocation type definition: https://reactrouter.com/docs/en/v6/hooks/use-location

Thus, you can use a cast to cast the state type as any to avoid those errors:

const location = useLocation();
const state = location.state as any;

Or, if you know the type of location.state, you can cast it to a custom object type:

const location = useLocation();
const state = location.state as { error?: { title: string; detail?: string } }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading