0

It's my first time using typescript and I'm getting a problem with the variable called "state" as it's use to get my list of users form the api but I get this error "'state' is of type 'unknown'" even though it actually works. As I said it's my first time with typescript and I dontu fully understand why it works if it has an error.

//React Imports
import React, { useEffect } from "react";
//MUI Imports
import Navbar from "../../Components/Navbar";
import Grid from "@mui/material/Grid";
import Box from "@mui/material/Box";
import Card from "@mui/material/Card";
import CardContent from "@mui/material/CardContent";
import { CardMedia } from "@mui/material";
import Typography from "@mui/material/Typography";
//Redux Imports
import { fetchAllUsers } from "../../redux/slices/users";
import { useDispatch, useSelector } from "react-redux";

function Users() {
  const { list: users } = useSelector((state) => state.users);//Error in state.users

  const dispatch = useDispatch();

  useEffect(() => {
    dispatch(fetchAllUsers() as any);
  }, [dispatch]);

  return (
    <div className="Users">
      <Navbar></Navbar>
      <br></br>
      <Box sx={{ flexGrow: 1 }}>
        <Grid container spacing={2} alignItems="center" justifyContent="center">
          {users.map((user, index) => (
            <Grid item xs={3.1}>
              <Card>
                <CardMedia
                  component="img"
                  image={user.avatar}
                  alt="avatar image"
                ></CardMedia>
                <CardContent>
                  <Typography gutterBottom variant="h5">
                    {user.first_name} {user.last_name}
                  </Typography>
                  <Typography gutterBottom variant="h6">
                    {user.email}
                  </Typography>
                </CardContent>
              </Card>
            </Grid>
          ))}
        </Grid>
      </Box>
    </div>
  );
}

export default Users;


1

2 Answers 2

1
  const { list: users } = useSelector((state:SPECIFYTYPEHERE) => state.users);//Error in state.users

You need to specify the type of state after the colon in typescript otherwise the state will be inferred as unknown.

Sign up to request clarification or add additional context in comments.

Comments

1

You have to either include type definition for state in here (which you've probably written in the reducer part) or you can use conditional chaining state!.users or state!.users or you can give any as the type to state (state:any)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.