search

Home  >  Q&A  >  body text

Pass array to component

<p>I am new to React and need help with the following..</p> <p>I have a component that accepts a list of arrays to render the component and need a separate component to manipulate the array</p> <p>Rendered component: </p> <pre class="brush:php;toolbar:false;">export function DashboardContent() { return ( <Grid> <Grid.Col sm={12} md={12} lg={4}> <ProfileCard /> </Grid.Col> <Grid.Col sm={12} md={12} lg={8}> <Flex direction="column" h="100%" justify="space-between" gap="md"> <WelcomeCard /> <StatsGroup data={mockData} /> </Flex> </Grid.Col> <Grid.Col sm={12} md={12} lg={8}> <BalanceCard /> </Grid.Col> <Grid.Col sm={12} md={12} lg={4}> <OverviewCard /> </Grid.Col> </Grid> ); }</pre> <p>mockData is where I need to pass the array through the API call Currently passing the following simulation data: </p> <pre class="brush:php;toolbar:false;">export const mockData = [ { title: 'ABC', value: '$7,999', diff: 50, }, { title: 'XXX', value: '$4,00', diff: -13, }, { title: 'Null', value: '$ 0.745', diff: 1, }, ];</pre> <p>Need the help of a new component js that can independently manage and make API calls and pass arrays in the format described in the simulation.</p> <p>Been trying the following code with no success, any help would be greatly appreciated</p> <pre class="brush:php;toolbar:false;">import React, { useEffect, useState } from 'react'; import axios from 'axios'; interface CustomArray { title: string; value: string; diff: number; } const token = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'; const axiosInstance = axios.create({ headers: { Authorization: `Bearer ${token}`, }, }); const Usage = () => { const [users, setUsers] = useState([]); const fetchUsers = async () => { const response = await axios.get( 'https://myrestservices.com/api/v2/organizations/AXZ/usage' ); const usersData = response.data; const usersArray = usersData.map(user => ({ title: user.title, value: user.value, diff: user.diff, })); setUsers(usersArray); }; useEffect(() => { fetchUsers(); }, []); return users; }; export default Usage;</pre> <p><br /></p>
P粉006540600P粉006540600456 days ago548

reply all(1)I'll reply

  • P粉352408038

    P粉3524080382023-08-16 00:58:35

    The first thing that needs to be done is to change the implementation of Usage to something similar to react custom hooks

    const useApiData = (apiUrl) => {
      const [data, setData] = useState([]);
    
      const fetchData = async () => {
        try {
          const response = await axios.get(apiUrl);
          const responseData = response.data;
    
          const dataArray = responseData.map(item => ({
            title: item.title,
            value: item.value,
            diff: item.diff,
          }));
    
          setData(dataArray);
        } catch (error) {
          console.error('Error fetching data:', error);
        }
      };
    
      useEffect(() => {
        fetchData();
      }, [apiUrl]);
    
      return data;
    };
    
    export default useApiData;

    Then make the following changes inside the StatsGroup component to render this data.

    const StatsGroup = ({ apiData }) => {
      return (
        <div>
          {apiData.map(item => (
            <div key={item.title}>
              <p>Title: {item.title}</p>
              <p>Value: {item.value}</p>
              <p>Diff: {item.diff}</p>
            </div>
          ))}
        </div>
      );
    };
    
    export default StatsGroup;

    So, to establish a link between a custom hook and the StatGroup component, first call the custom hook and then after getting the result pass the data to the StatGroup component's prop as shown below.

    const DashboardContent = () => {
      // 使用您想要从中获取数据的任何API URL
      const apiUrl = 'https://myrestservices.com/api/v2/organizations/AXZ/usage';
      
      const apiData = useApiData(apiUrl);
    
      return (
        <div>
          <h1>Stats Group</h1>
          <StatsGroup apiData={apiData} />
        </div>
      );
    };
    
    export default DashboardContent;

    reply
    0
  • Cancelreply