Quantcast
Channel: Active questions tagged react-native+typescript - Stack Overflow
Viewing all articles
Browse latest Browse all 6215

How to update state properly in react hooks

$
0
0

So, The problem is that whenever I press the delete button, it just removes the deletes the last input and the button regardless of the index. I've tried to change the key to key={${index}${name}}`, this won't work that well, because the inputs are changeable (in main code) and that makes thing messed up.How can I make delete properly according to indexes??

function App() {  const [names, setNames] = React.useState(["First", "Second",'third','fourth']);  const onNameDelete = useCallback((index: number) => {    setNames((prev) => {      const name = names[index];      return prev.filter(x => x != name);    });  }, [names]);  return (<div>      {names.map((name, index) => (<Child          key={index}          name={name}          index={index}          onDelete={onNameDelete}        />      ))}</div>  );}interface ChildProps {  name: string;  index: number;  onDelete: (index: number) => void;}export const Child: React.FC<ChildProps> = React.memo(  ({ name, index, onDelete }) => {    return (<div><input          defaultValue={name}        /><button onClick={() => onDelete(index)}>delete</button></div>    );  }

Viewing all articles
Browse latest Browse all 6215

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>