How to handle restAPI and redux with Lit-Element?

508 views Asked by At

I'm using Javascript, Lit-Element, Express, Mongoose and Redux.

I don't know why, but when I click on a link that do a GET request the page-view is not re-rendered correctly. Probably it's a problem with redux because I didn't have this problem before I modified my app with redux.

For example, if I click on this button, the url on the address bar is changed from 'localhost/items' to 'localhost/items?color=red', but OFTEN the page-view is the same as before: I don't see my filtered list of 'items', but all the items. SOMETIMES the filter button works.

<a href='/items?color=red'><button @click="${()=>updateList('color=red')}">Show red items</button></a>

updateList(filter) function:

updateList(filter){
    store.dispatch(fetchItemsList(filter));
}

Redux action:

export const fetchItemsList = (searchParams) => (dispatch) => {
    fetch(`/api/items?${searchParams}`)
      .then(res => res.json())
      .then(res => dispatch(updateItems(res)))
      .catch(err => console.log(err));
  };
  
  const updateItems = (list) => {
    return {
      type: UPDATE_ITEMS_LIST,
      list: list
    };
  };

Reducer:

const START_STATE = {
    list: []
};

const features = (state = START_STATE, action) => {
    switch (action.type) {
        case UPDATE_ITEMS_LIST:
            return action.list.reduce((o, item) => ({...o, [item._id]: item}), {});
        default:
            return state;
    }
 };

Basically I have a table with a list of items with different features, one of these is the item color. I want to use rest api to filter my items list.

Can you help me?

1

There are 1 answers

0
Keith On

There are a lot of fire-and-forget promises here - they go do something, but nothing comes back to the LitElement to tell it that it has an update to render.

You need something to go back to the LitElement and either set an observed property or call requestUpdate().

A good way to do this with Redux would be a ReactiveController that manages your Redux actions and calls this.host.requestUpdate() when there are changes to re-render.