reactjsreduxreact-hoc

useEffect not setting data to state in functional component


I have functional component wrapped with HOC. Its returns some props after api call. How do I set the state in my child component(functional).

const withEditHoc = (WrappedComponent, actioneffects) => {
  class HOC extends Component {
    constructor(props) {
      super(props);
      this.state = {
        loading: true,
      };
    }
    executeAllActions = async (data, id) => {
      await Promise.all(data.map(act => this.props.dispatch(act(id)))).then(() =>
        this.setState({ loading: false }),
      );
    };
    componentDidMount = () => {
      const editpageId = this.props.match.params.id;
      this.executeAllActions(actioneffects, editpageId);
    };
    render() {
      console.log(this.state.loading);
      return (
        <React.Fragment>
          <Loading loading={this.state.loading}>
            <WrappedComponent {...this.props} />
          </Loading>
        </React.Fragment>
      );
    }
  }
  return HOC;

This is my HOC Structure. After the api call the data will be in redux. I am getting a prop for my functional component using mapToStateProp.(react version 16.3) Please any suggestion for this.

Functional component

function ProjectDetails(props) {
  const [projectValue, setValue] = useState({});
  const [proData, setProData] = useState({ ...props.project });

  useEffect(() => {
    setProData({ props.project });//Here I need to set my data, Iam not able to set data here.

  }, []);

  return <div>{JSON.stringify(props.project)}</div>;
}
function mapStateToProps(state) {
  return {
    project: state.projects.project,
  };
}



const projectDetailsWithHocLoading = withEditHoc(ProjectDetails, [actions.apiCall()]);
export default connect(mapStateToProps, null)(projectDetailsWithHocLoading);

I am a beginner to react. Please suggest a good way


Solution

  • mapStateToProps created for class components. because you are using hooks, you should use useSelector hook


       import { useSelector } from 'react-redux';
    
       function ProjectDetails(props) {
         const [projectValue, setValue] = useState({});
         const proData = useSelector(state => state.projects.project)
    
         return <div>{JSON.stringify(proData)}</div>;
        }
    
      const projectDetailsWithHocLoading = withEditHoc(ProjectDetails,actions.apiCall()]);
      export default projectDetailsWithHocLoading;