user image

nico
Published in : 2022-02-18

How to update the props property of type array after filtering in one functionnal component

React js

Hello I need to filter props.arrayData with filtering in one functionnal component

export function BurnSegments({ arrayData }) {

 function handleChange(event) {

        event.preventDefault();
        
        this.setState({ arrayData : arrayData .filter(b => b.key === event.target.value) });
        

    }

 

But setState is undefined, so what is the proper way of changing arrayData in the props?

Thanks

 


 

 

 

Comments

nico Date : 2022-02-18

Best answers

4

Best answers

4

I made it work by using the useState of the functional component as we can't update props.

with the steps:

 

  • create a State with useState in the functional component called statearrayData (to distinct it from the props called arrayData)
  • in the useEffect : update the state with the props arrayData by using setStatearrayData ==> triggered on the first render and when redux state is updated
  • in the handleChange we also use setStatearrayData ==> we can filter the props and update the component state
     

By the way I used redux here


export function Sample({ arrayData}) {

    const [statearrayData , setStatearrayData ] = useState([]);
    
     useEffect(() => {


       // we update here the state with the prop
        setStatearrayData (arrayData);


    }, [arrayData]);


    function handleChange(event) {

        event.preventDefault();
		setStatearrayData(arrayData.filter(b => b.key === event.target.value));
 
    }

}

function mapStateToProps(state) {
    return {
        arrayData: state.arrayData
    };
}

function mapDispatchToProps(dispatch) {
  ....
}

export default connect(mapStateToProps, mapDispatchToProps)(Sample);
    

Leave a comment

Join us

Join our community and get the chance to solve your code issues & share your opinion with us

Sign up Now

Related posts

React Component setState doesn't update my property
Publish date: 2022-03-29 | Comments: 2

Tag: React js

[solved] Reactjs is not updating the props
Publish date: 2022-02-04 | Comments: 2

Tag: React js

React Component displaying a list of lines
Publish date: 2022-03-19 | Comments: 3

Tag: React js

import link as router link from 'react-router-dom' Reactjs
Publish date: 2021-09-30 | Comments: 3

Tag: React js

How to use Datepick of Mui with Formik
Publish date: 2022-02-14 | Comments: 6

Tag: React js

Best way to update the state in one class component from the redux store?
Publish date: 2022-03-30 | Comments: 3

Tag: React js