0

I'm still beginner with ReactJs. Actually I want to rewrite my class components to hook components but I have a problem with one part of my code. Anyone can help me with rewrite this component to hook?

This is my code:

class App extends Component {
  state = {
    selected: {},
    data: data,
    filtered: data
  };

  handleChange = data => {
    if (data == null) {
      this.setState({
        filtered: this.state.data
      });
    } else {
      this.setState({
        selected: data,
        filtered: this.state.data.filter(d => d.client_id === data.id)
      });
    }
  };

  returnClientNameFromID = id => options.find(o => o.id === id).name;

  render() {
    const {
      state: { selected, data, filtered },
      handleChange
    } = this;


    return ( <div>
    ...
1
  • You seem to be running your current code on a magical computer that can assign a not previously declared value called data to state.data and state.filtered without throwing an error. Commented Apr 10, 2020 at 18:51

1 Answer 1

1

Here's what you could do. With useState you always have to merge objects yourself setState((prevState) => {...prevState, ... })

const App = () => {
  const [state, setState] = useState({
    selected: {},
    data: data,
    filtered: data
  })

  const handleChange = data => {
    if (data == null) {
      setState((prevState) => {
        ...prevState,
        filtered: this.state.data
      });
    } else {
      setState((prevState) => {
        ...prevState,
        selected: data,
        filtered: prevState.data.filter(d => d.client_id === data.id)
      });
    }
  };

  const returnClientNameFromID = id => options.find(o => o.id === id).name;

  const { selected, data, filtered } = state

  return() (
    <div> ... </div>
  )
}
Sign up to request clarification or add additional context in comments.

1 Comment

No problem, I tried my best to keep it as simple as possible :) Could you accept the answer, if it works?

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.