jeudi 22 avril 2021

React - Component that strictly depends on context

Have you ever been in a use case where a component strictly depends on a context?

Imagine this situation:

  1. Make a fetch to the same amount to data.

  2. Save the data in a map, in a context

  3. Only after the context state update has finished, render all the data in a FlatList

    3.1 Then pass an id to the component.

      <MyComponent id={id} /> 
    

    3.2 The component, which is a consumer of the context, does:

     const {isLiked} = myContext.getItem(id); // Get a most fresh prop from the context
    

    3.3 The component renders everything using the context data

Not sure if this is a good design, but saving data in a context after fetches is a requirement for my use case.

As you can see, now my component strictly depends on a Context, because if data is not in the context, then it will simply fail.

Should I be more flexible? and pass "falsy" props to it (just to prevent the situation of using this component without storing data in context)?

<Card id={id} isLiked={isLiked} />

Is it a bad design no have components strictly depending on Context API?

Aucun commentaire:

Enregistrer un commentaire