-1

I am trying to get some data into a table. For that I am using react Map() function. But the variable is inside the function and I am unable to use it in map. What is the easiest way to use that variable in map.

This is my coding

import React, { useEffect } from 'react';
import { useDispatch } from 'react-redux';
import { getAllActivityDetails } from 'app/store/activityTracker/activitySlice';

const ActivityLog = () => {
    const dispatch = useDispatch();

useEffect(() => {
    getAllActivities();
}, []);

const getAllActivities = async () => {
    const user = await JSON.parse(localStorage.getItem('user'));
    const paramsData = {
        _entity: 'ActivityTrack',
        _select: '*',
        channel: 'KOORS',
        email: user && user.data && user.data.email ? user.data.email : ''
    };
    console.log('Email', user);
    const res = await dispatch(getAllActivityDetails(paramsData));
    console.log('res', res);
};

return (
    <div className="flex flex-col mt-8">
        <div className="py-2 -my-2 overflow-x-auto sm:-mx-6 sm:px-6 lg:-mx-8 lg:px-8">
            <div className="inline-block min-w-full overflow-hidden align-middle border-b border-gray-200 shadow sm:rounded-lg">
                <table className="min-w-full">
                    <thead>
                        <tr>
                            <th className="px-6 py-3 text-xs font-medium leading-4 tracking-wider text-left text-gray-100 uppercase border-b border-gray-200 bg-gray-50">
                                .
                            </th>
                            <th className="px-6 py-3 text-xs font-medium leading-4 tracking-wider text-left text-gray-900 uppercase border-b border-gray-200 bg-gray-50">
                                Actions
                            </th>
                            <th className="px-6 py-3 text-xs font-medium leading-4 tracking-wider text-left text-gray-900 uppercase border-b border-gray-200 bg-gray-50">
                                Users
                            </th>
                        </tr>
                    </thead>

                    <tbody className="bg-white">
                        {res.data.data.map(log => (
                            <tr>
                                <td className="px-6 py-4 whitespace-no-wrap border-b border-gray-200">
                                    <div className="flex items-center">
                                        <div className="ml-4">
                                            <div className="text-sm font-medium leading-5 text-gray-600">
                                                {log.userName}
                                            </div>
                                            <div className="text-sm font-medium leading-5 text-gray-800">
                                                {log.createdAt}
                                            </div>
                                        </div>
                                    </div>
                                </td>

                                <td className="px-6 py-4 whitespace-no-wrap border-b border-gray-200">
                                    <div className="text-sm leading-5 text-gray-800">{log.activityCode}</div>
                                </td>

                                <td className="px-6 py-4 whitespace-no-wrap border-b border-gray-200">
                                    <div className="text-sm leading-5 text-gray-800">{log.description}</div>
                                </td>
                            </tr>
                        ))}
                    </tbody>
                </table>
            </div>
        </div>
    </div>
);
};

export default ActivityLog;

I need to use the 'res' variable in the map. But it is showing as res is not defined.

This is the response I am getting[unable to share complete result]

Response

Trying to do this since morning. If I create any outer variables, other functions related to this are changing. So how can I get the details in map without changing anything in the current code? Please help.

I just need to get the values of 'res' globally.

4
  • The problem isn't clear. What are you trying to get from res, and how do you use it that it causes to fail. Please provide a minimal and reproduicble code. Commented Oct 6, 2021 at 12:27
  • You can return res from that function and use that function to map Commented Oct 6, 2021 at 12:29
  • Lets say I am going to get Id and activityCode form the array. How can I get that via a map function. Commented Oct 6, 2021 at 12:29
  • or you can use state Commented Oct 6, 2021 at 12:30

3 Answers 3

1

You can use useState and then map.

const [arr,setArr]=useState([]);

const getAllActivities = async () => {
    const user = await JSON.parse(localStorage.getItem('user'));
    const paramsData = {
        _entity: 'ActivityTrack',
        _select: '*',
        channel: 'KOORS',
        email: user && user.data && user.data.email ? user.data.email : ''
    };
    const res = await dispatch(getAllActivityDetails(paramsData));
     setArr(res.data.data) //According to your response

And then you can use map like

arr?.map(//Your code)

And by the way it seems you are using redux, you can directly store the data in store. I don't know how you are using your workflow

Sign up to request clarification or add additional context in comments.

6 Comments

This may work. However, we know that dispatch() function will return a value of the dispatched action itself. But seeing data returned, we don't see plain JS object which should contain properties : type and (additional) payload. Instead, the value returned looks more like the state of the store. I wonder how the original poster defined his actions in the slice as well as the store. Imo, this is not a correct of way of using Redux.
Dispatch is supposed to tell the store to update its states, and we don't really care for its return value from which we use it for rendering purpose. React-Redux provides useSelector method which we can use to get the data/state from the store for rendering our component. I suggest the original poster read Redux official tutorial doc from part 1 : redux.js.org/tutorials/essentials/part-1-overview-concepts, through the whole parts of the tutorial in order to use Redux correctly. Redux team also recommend using Redux Toolkits for easier coding which is also covered in the tutorials.
I also don't know how op has managed his workflow. But you can see op's console.log and it gives him the objects he need. I also mentioned him it is not correct way to do so
Assuming that his store data is shown like in the variable named res that contains property of nested array, namely res.data.data. Then just import useSelector from React-Redux; so we can use useSelector method like the following : const res = useSelector(state => state.data.data). This code must placed at the top level of his function component. No need to return a value from dispatch() method. Everytime an action is dispatched, useSelector() method will run for checking updates to determine re-rendering. Hence, he can just use this res variable in his rendering for the table.
We have not seen his full code. We don't know how he has managed his store. I know dispatching action will update the state in global store. From this post, I have assumed op doesn't have enough redux knowledge and it's workflow
|
0

You have to place first the function and then the useEffect. By the way, when you call getAllActivities in that useEffect, are you storing the data in redux? if so you can use that data to map, if not, you need to store that data in the state and then map it. Im not sure if i understand what you need

1 Comment

You mean create a const [log, setLog] = useState([]); and the setLog(reg) inside the getAllActivity, and then use log.map() ? But that is showing as log.map is not a function
0

Assuming that we can accept how your workflow as is, in which you use the data for this component only, then one way to solve your problem without need of additional local state is to use useRef() : useRef hook.

useRef is not only used for accessing DOM, but can also be used like instance variable/field in class component. See : Is there something like instance variables in Hooks ?

Put the following in the top level of your component :

const resref = useRef({}); // the variable name can be any valid name

then inside your getAllActivities function, assign the value of res to resref.current like so :

const res = await dispatch(getAllActivityDetails(paramsData));
resref.current = res;

or you can simply write like so :

resref.current = await dispatch(getAllActivityDetails(paramsData));

In your rendering of the table, replace :

res.data.data

with

resref.current.data.data

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.