0

I removed the imports because they are not a problem

In my render, I set my state and it shows it to me in the console, but when I try to map it, it is null and it says to me that there are no elements in the state "allInfo", how can I fix this error so that my state updates?

class Friends extends Component {

constructor(props) {
    super(props)
    this.state = {
        allInfo: []
    }
}

render() {

    fetch('https://localhost:44314/api/Users')
        .then(response => response.json())
        .then(data => {
            this.setState(prevState => {
                allInfo: data.map((obj) => { prevState.allInfo.push(obj) })
            })
        })

return (
    <div>
        <NavMenu />
        <div style={{ fontSize: 38, textAlign: "center", color: "white" }}>FRIENDS</div>
        <TableContainer component={Paper}>
            <Table aria-label="simple table">
                <TableHead>
                    <TableRow>
                        <TableCell>Users</TableCell>
                        <TableCell align="right">Follow</TableCell>
                    </TableRow>
                </TableHead>
                <TableBody>
                    {this.state.allInfo.map((row) => (
                        <TableRow key={row.username}>
                            <TableCell component="th" scope="row">
                                {row.username}
                            </TableCell>
                            <TableCell align="right">Follow?</TableCell>
                        </TableRow>
                    ))}
                </TableBody>
            </Table>
        </TableContainer>
  </div>
);

} }

export default Friends

Patrick Youssef
  • 109
  • 1
  • 7

2 Answers2

1
fetch('https://localhost:44314/api/Users')
    .then(response => response.json())
    .then(data => {
        this.setState(prevState => {
            allInfo: data.map((obj) => { prevState.allInfo.push(obj) })
        })
    })

Push returns the length of the array.

You should just use:

this.setState(prevState => {
            allInfo: data
        })
tgreen
  • 1,720
  • 1
  • 16
  • 28
0

Man many things, you are using fetch and then, that's not recommended any more, use


async render() {

   let response = await fetch('https://localhost:44314/api/Users')
            this.setState(prevState => {
                allInfo: data.map((obj) => { prevState.allInfo.push(obj) })
            })

but more explaining your problem, you this reference is not part of the then scope, so you are acessing a null value, wich will give you an error.