Home > Software engineering >  Return and display data, but with condition
Return and display data, but with condition

Time:02-16

I have this "api" and through it a group of users is returned, then I display the users in a table, and the form of the data that is returned based on the written code is:

enter image description here

And as it is clear in the picture, there are two variables within the data that have been returned, the first is “isActive” and the second is “isVerified”, and these two variables are either “false” or “true”.

The problem is that I want to return only the data in which the value of the two variables is true.

That is, data is returned from the backend, and this data is a group of users, and each user has two values "isActive" and "isVerified", and either I have these values "true" and either "false", but what is required is that I want to return the data and Displayed in table only when these two values are true.

How can I solve the problem?

export const getUsers = createAsyncThunk(
  "usersRequests/getUsersRequests",
  async (routeParams, { getState }) => {
    routeParams = routeParams || getState().usersApp.users.routeParams;
    const response = await axios
      .get("/users/for-admin", {
        params: routeParams,
      })
      .catch((err) => console.log(err));
    const usersRequestsData = response.data.data;
    console.log("data inside Slice:", usersRequestsData);
    return usersRequestsData;
  }
);

CodePudding user response:

The best way would be to add a query to your URL like so /?active=true&verified=true, and of course, add parsing and then logic to your backend, or you could create a separate route.

If the first solution isn't perfect for you, you can filter it in your front-end, I don't think filtering in async thunk is a good approach, you should filter it in your reducer.

const usersSlice = createSlice({
  name: 'users',
  initialState,
  reducers: {},
  extraReducers: (builder) => {
    builder.addCase(getUsers.fulfilled, (state, { payload }) => {
      state.users = payload.filter(u => u.isActive === true && u.isVerified === true);
    });
  },
});

CodePudding user response:

Just before the .catch, use a .then to prepare your data with a return filter, something like :

.then((res) => res.filter((item) => item.valueToEvaluate1 && item.valueToEvaluate2))

The doc to understand filter https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

Good ?

  • Related