3

I am having trouble understanding why this code is not working. It removes the item from the people array in the state but its not rerendering the list.

import { render } from 'react-dom';
import axios from 'axios';
import ReactLoading from 'react-loading';
import useMediaQuery from '@material-ui/core/useMediaQuery';
import People from './components/People';
import './style.css';

interface PeopleData {
  name: string;
  eye_color: string;
}
interface PeopleResponse {
  results: PersonagemData[];
}

const App: React.FC = () => {
  const [loading, setLoading] = React.useState(true);
  const [people, setPeople] = React.useState([]);
  const isMobile = useMediaQuery('(max-width:768px)');
  
  React.useEffect(() => {
    axios.get<PeopleResponse>('https://swapi.dev/api/people/').then(response => {
      setPeople(response.data.results);
      setLoading(false);
      console.log(response)
    })
  }, []);

  const deleteChar = React.useCallback(index => {
    let aux = people;
    aux.splice(index, 1)
    setPeople(aux);
  }, [people])

  return (
      <div>
          {loading ? (
            <ReactLoading
            type={'spin'}
            color={'#800080'}
            height={'10%'}
            width={'10%'}
            /> 
            ):
              people.map((element, index) => 
              (<People
              index={index} 
              name={element.name} 
              color={element.eye_color} 
              deleteChar={deleteChar}
              />))
          }  
        </div>
    );
}

render(<App />, document.getElementById('root'));

I don't understand why it isn't rerendering. I'm doing this on StackBlitz so you can test it on this link https://react-ts-j1kkcp.stackblitz.io

1 Answer 1

3

You need to destructure the new list: setPeople([...aux]); Otherwise React will think nothing has changed.

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

1 Comment

You're right! Now that you said it I totally remember the same thing happening to me before. Thanks.

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.