2021年2月3日星期三

Handling a Variable Number of `useState` in React App

The current React app that uses useState and useEffect shown below takes an object params from the user and uses it to query an API server to obtain the results chartData and tableData which are then displayed using the Chart and Table components. This works fine.

However, the app must now be modified to display multiple (and a variable number of) search results at the same time on both the Chart and Table components. There will always be a single Chart and a single Table component irregardless of the number of search params.

Question: This is where I am stuck! How do we maintain seperate useState and useEffect, one for each set of search params so that when only one of the search params is changed, not all the searches will need to be done, since these params remained unchanged. Additionally, all the chartData from all the different search params will be combined together and passed inth the Chart component, similarly for the TableData and its Table component.

Current App

  export function Main() {      const [ params, setParams ] = useState({name: 'foo'});      const [ chartData, setChartData ] = useState([]);      const [ tableData, setTableData ] = useState([]);        useEffect(() => {          axios              .get('http://localhost/chart', {params: params})              .then(response => {                  setChartData(response.data)              })            axios              .get('http://localhost/table', {params: params})              .then(response => {                  setTableData(response.data)              })      }, [params])        return (          <div>              <Chart data={chartData} />              <Table data={tabletData} />          </div>      )  }  

Edit: I am thinking of the following data structure, but can not figure out how to create the React hooks and its dependency arrays...

searches = [      {          name: 'foo',          params: {...},          chartData: [{}, {}, ...],          tableData: [{}, {}, ...],      },      {          name: 'bar',          params: {...},          chartData: [{...}, ...],          tableData: [{...}, ...],      },      ...  ]  
https://stackoverflow.com/questions/66037950/handling-a-variable-number-of-usestate-in-react-app February 04, 2021 at 08:59AM

没有评论:

发表评论