David Ho
David Ho

Reputation: 287

(Material-table)Unable to fetch my option list to lookup field of the table column

Currently, I have a useEffect code like this, trying to obtain my preset options from axios get request and send it to the lookup field of the table column

  const [optionList, setOptionList] = useState({});


  const [columns, setColumns] = useState({
    columns: [
      {
        title: 'Image_ID',
        field: 'image_ID',
        lookup: optionList,
      },
    ]
  });

  useEffect(() => {
    const getOption = async () => {
      let data = [];
      let options = {};
      const response = await axios.get(sampleUrl);
      const { data: { image_sample } } = response;
      image_sample.map((item) => {
        data.push(item.image_ID);
      });
      data.forEach(item => options[item] = item);
      setOptionList(JSON.stringify(options));
    }
    getOption();
  }, [])

Everything went well in the console, my optionList look exactly what I wanted: {"p01":"p01","p02":"p02","p03":"p03"} However, the table options remained empty. But if you directly fetch the optionList manually to the column like this:

  const [columns, setColumns] = useState({
    columns: [
      {
        title: 'Image_ID',
        field: 'image_ID',
        lookup: {"p01":"p01","p02":"p02","p03":"p03"},
      },
    ]
  });

It will work for some reason. At some point, I suspect the optionList has already been sent to the table before my useEffect was mounted. Anyone has an idea what's happening?

Upvotes: 0

Views: 315

Answers (1)

VMT
VMT

Reputation: 819

Because initialize of columns.columns[0].lookup state have set by value of optionList. In the first render, this state recieve a {} until useEffect call, inside useEffect setOptionList was called to change optionList state, optionList had change but column state not change cause this component not re-render to show what you want to see.

If you want fix it, just add useEffect with dependencies includes optionList and have function setColumns:

const [optionList, setOptionList] = useState({});


  const [columns, setColumns] = useState({
    columns: [
      {
        title: 'Image_ID',
        field: 'image_ID',
        lookup: optionList,
      },
    ]
  });

  useEffect(() => {
    const getOption = async () => {
      let data = [];
      let options = {};
      const response = await axios.get(sampleUrl);
      const { data: { image_sample } } = response;
      image_sample.map((item) => {
        data.push(item.image_ID);
      });
      data.forEach(item => options[item] = item);
      setOptionList(JSON.stringify(options));
    }
    getOption();
  }, [])

  useEffect(() => {  // <== Add this useEffect
    setColumns({
     columns: [
      {
       title: 'Image_ID',
       field: 'image_ID',
       lookup: optionList,
      },
     ]
   }) 
  }, [optionList])

Upvotes: 1

Related Questions