Search code examples
javascriptreactjstypescriptrenderinguse-state

React - Removing item from array not rerendering list


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


Solution

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