score:1
i ended up doing similar as @tmhao2005 mentioned. my final solution looks like the following. i wanted to do this to be able to decouple table logic (selection, deletion, etc..) from presentation logic. so that i can create a generic-table'ish component (not showcased in the example below)
const rootelement = document.getelementbyid("root");
const {
table,
tablebody,
tablecontainer,
tablehead,
tablecell,
tablerow,
link
} = materialui;
// to mimic async loading of data
function usedata() {
const [data, setdata] = react.usestate([]);
react.useeffect(() => {
settimeout(() => setdata([1, 2, 3]), 0);
}, []);
return {
data,
deletebyindex: (idx) => {
// some random function to mutate the state
setdata(data.filter((_, index) => idx !== index));
}
};
}
function reducer(state, action) {
switch (action.type) {
case "init":
return { ...state, items: action.items };
default:
throw new error("unknown action");
}
}
function usetable(initialitems) {
const isfunctioncreator = react.usememo(
() => typeof initialitems === "function",
[initialitems]
);
const [state, dispatch] = react.usereducer(reducer, {
items: isfunctioncreator ? null : initialitems,
selecteditems: [],
allselected: false
});
const data = isfunctioncreator ? initialitems() : null;
react.useeffect(() => {
if (isfunctioncreator && data) {
dispatch({ type: "init", items: data });
}
}, [isfunctioncreator, data]);
return {
...state
};
}
const app = () => {
const { data, deletebyindex } = usedata();
const ctrl = usetable(() => data);
if (!data) return <div>loading</div>;
return (
<tablecontainer>
<table>
<tablehead>
<tablerow>
<tablecell>item</tablecell>
<tablecell align="center" size="small"></tablecell>
</tablerow>
</tablehead>
<tablebody>
{ctrl.items &&
ctrl.items.map((item, idx) => (
<tablerow key={item}>
<tablecell>{item}</tablecell>
<tablecell align="center" size="small">
<link onclick={() => deletebyindex(idx)}>delete</link>
</tablecell>
</tablerow>
))}
</tablebody>
</table>
</tablecontainer>
);
}
// react bootstrap
reactdom.render(
<react.strictmode>
<app />
</react.strictmode>,
rootelement
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.1/umd/react-dom.production.min.js"></script>
<script src="https://unpkg.com/@material-ui/core@latest/umd/material-ui.production.min.js"></script>
<div id="root"></div>
score:2
that's interesting question. because hook of react.usereducer
is only take the initial value once, then it will maintain the state itself without setting value again.
so the idea is quite simple. you just simply set the your state again via the dispatch
function you exported every time your data
has been changed. here is the idea snippet:
let's create a exported function to update your state in usetable.ts
:
return {
setdata: data => dispatch(/* this is where you set your state again */)
}
now call setdata
right your data
changed in your main file:
const { setdata, ...others } = usetable(data);
react.useeffect(() => {
if (data) {
// this will sync your state with the latest data
setdata(data);
}
}, [data])
Source: stackoverflow.com
Related Query
- Initialising a useReducer with async data in a hook
- React Hook useEffect : fetch data using axios with async await .api calling continuous the same api
- React useReducer async data fetch
- Async data flow in React App with Redux + ReactRouter?
- Initialize component with Async data
- Server side rendering with async data fetch
- redux react strategy with async data and interaction
- State management with useContext and useReducer and fetching data with useEffect
- Fetch data with a custom React hook
- fetch data from multiple apis with async await
- Refreshing data fetched with a custom hook after closing a modal
- useState hook not initialising with correct value: Array
- React hook form with redux and async request
- How to make a react component with Async data re-usable in Redux flow?
- react.js - Deep Object in state with async data does not work
- fetching data with react hook returns undefined on nested obj properties
- React hook forms with nested fields array from an async source returns empty array
- REACT: How to create a reusable custom hook with functions and effects that can change & react to changes in a host component's data
- Use data from async function on React State with JSX
- UseEffect hook does not work or how to display async data
- Data re rendering with useIonViewDidEnter hook in Ionic React
- How to use onChange with react hook on react select to change data base on user select
- I am using React Hook Form with Typescript, string does not accept incoming data
- how to test a hook with async state update in useEffect?
- React and redux usage with async data fetching
- Using context Api with useReducer hook in next.js gives undifined back when useContext is called
- Issues rendering data fetched with useEffect in a custom hook
- SetState with react hook and redux after async call to axios API
- Cancel an async request with useInterval hook
- Proper async await syntax for fetching data using useEffect hook in React?
More Query from same tag
- How to dynamically change animation value in inline syle of ReactJS
- Webpack alias for src folder in React app?
- how to handle click only one <li> item in react
- React sending array of objects as form Data
- Firebase realtime not working correctly on React
- Role Authorization Not Working with React/ASP.NET Core API
- Component loading and transition animations with react-router
- Test if props are passed (Without using Enzyme)
- Find First Iteration of Map in React/Javascript
- React router redirect to root blank page
- How can I redirect a /:user link to 404 page in react redux
- passing multiple data on a link click in reactjs
- Google Places Autocomplete along with google maps - load issue
- react-router 2.0 doesn't route
- Filter on two arrays same time?
- React-router: nested routes error
- Fetch testing using jest
- Generate embedded gist within html string retrieved from Firebase - React
- triggering CSS animation with useRef() in React
- CORS header ‘Access-Control-Allow-Origin’ missing from Wikipedia API response
- On closing a particular tab it closes all the tabs
- Can I turn off create-react-app chunking mechanism?
- First react code
- Antd File upload not getting reset
- Is it correct to use dom-to-image module in reactjs app?
- map.setView is not a function
- Getting warning "Warning: Each child in a list should have a unique "key" prop." when my component render
- .NET Core 3.1 with ReactJs 16.9.0 - Run in IIS sub-folder
- Why local variables in React functional component?
- How to make a test that will wait 5 seconds before check element appearance (React testing lib)