Nimish goel
Nimish goel

Reputation: 2771

Customize the Api response and use it later on other React components

I am from angular background, just started with React.js. This question can be easy for you all, But architecture wise, I need a good solution.

After getting the json response from API, I want to modify the response and then save it somewhere, so i can use modified response on multiple components. (Json modification is not a issue, I want to know, what is the best solution to store the response then where to modify the response and then where to store so other components can use the modified version of it. I am not using redux.)

For example, If i get the below response from axios api

{
  "name":"John",
  "age":30,
  "cars": [
    { "name":"Ford", "models":[ "Fiesta", "Focus", "Mustang" ] },
    { "name":"BMW", "models":[ "320", "X3", "X5" ] },
    { "name":"Fiat", "models":[ "500", "Panda" ] }
  ]
 }

I want to modify it first like

{
  "name":"John",
  "age":30,
  "cars": [
    { "name":"Ford", "models":[ "Fiesta", "Focus", "Mustang" ] },
    { "name":"BMW", "models":[ "320", "X3", "X5" ] },
    { "name":"Fiat", "models":[ "500", "Panda" ] }
  ],
  "newparameter": [
    { "name":"fdf" }
    
  ]
 }

After modifying this, I want to save it any service or something. So i can use it later on on other components irrespective of there is not relation between of components.

Upvotes: 0

Views: 307

Answers (1)

HMR
HMR

Reputation: 39310

Json modification is not a issue, I want to know, what is the best solution to store the response then where to modify the response and then where to store so other components can use the modified version of it. I am not using redux

You can lift state, use a state manager (redux) or react context, here is an example of Context

const DataContext = React.createContext();
const DataProvider = ({ children }) => {
  const [dataResult, setDataResult] = React.useState({
    loading: true, //not using error as well
  });
  //fetch the data when the application loads
  React.useEffect(() => {
    setTimeout(
      () =>
        setDataResult({ loading: false, data: [1, 2, 3] }),
      2000
    );
  }, []);
  return (
    <DataContext.Provider value={dataResult}>
      {children}
    </DataContext.Provider>
  );
};

const data = ['a', 'b', 'c', 'd'];
function App() {
  const { loading, data } = React.useContext(DataContext);
  return (
    <div>
      {loading ? (
        'loading'
      ) : (
        <pre>{JSON.stringify(data, undefined, 2)}</pre>
      )}
    </div>
  );
}

ReactDOM.render(
  <DataProvider>
    <App />
  </DataProvider>,
  document.getElementById('root')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>


<div id="root"></div>

Upvotes: 1

Related Questions