Hamid
Hamid

Reputation: 1760

why nested array object not work in react component

There is a grid component what receive a prop as searchElement to rendering search segment of the grid.some dropdowns options is empty and should fill by async request after component mounted. after I call async fetch in componentDidMount and assign new options to searchElements something is wrong because in grid component console.log show searchElements[0] have a property as options which contains array with many elements but when I do console.log searchElements[0].options it's empty !!!!!

let SearchTerms = [
    {
        key    : "supervisor",
        label  : "Supervisor",
        type   : GRID_DROPDOWN_TYPE,
        options: [],
        col    : 2
    },
.
.
.
    class CommentComponent ..... {
    ...

async componentWillMount() {
    let GetSupervisors = await fetchWith(`${entry_point}/users`, "GET", {roles: 5}, dispatch, true);
    if (GetSupervisors.ok && GetSupervisors.result['hydra:totalItems'] > 0) {
                    Supervisors = GetSupervisors.result['hydra:member'];
    }

    SearchTerms[0].options = Supervisors.map(data => ({
         value: data.id,
         label: data.fullname
    }));
}

then I'll pass SearchTerms to GridComponent

<GridComponent searchElements={SearchTerms} ...

Now in GridComponent :

getSearchElements = () => {
        const {searchElements, preloader, process, searchMode} = this.props;
        console.log(searchElements[0]);
        let SearchElements = [];

Problem is here : When I come to CommentComponent through Route Click everything is ok but When I refresh the page SearchElement[0].options is empty :(

Upvotes: 0

Views: 56

Answers (1)

Scc
Scc

Reputation: 516

Use SearchTerms as the state

class CommentComponent ..... {
 state = {
    SearchTerms: [
    {
        key    : "supervisor",
        label  : "Supervisor",
        type   : GRID_DROPDOWN_TYPE,
        options: [],
        col    : 2
    },
}
.
.
.

  async componentWillMount() {
    let GetSupervisors = await fetchWith(`${entry_point}/users`, "GET", {roles: 
 5}, dispatch, true);
    if (GetSupervisors.ok && GetSupervisors.result['hydra:totalItems'] > 0) {
                    Supervisors = GetSupervisors.result['hydra:member'];
    }

   const newSearchTerms = [...this.state.SearchTerms]
    newSearchTerms[0].options = Supervisors.map(data => ({
         value: data.id,
         label: data.fullname
    }));
    this.setState({SearchTerms:newSearchTerms })
}

Upvotes: 1

Related Questions