RTK Query documentation example throws error - reactjs

I am pretty much using the documentation example for fetching some data from a json file and I am getting this particular error:
react-dom.development.js:22839 Uncaught Error: Actions must be plain objects. Use custom middleware for async actions.
at Object.performAction (<anonymous>:1:31530)
at $ (<anonymous>:1:33343)
at Object.e (<anonymous>:1:37236)
at dispatch (<anonymous>:1:55003)
at buildHooks.ts:768:27
at commitHookEffectListMount (react-dom.development.js:23150:26)
at commitPassiveMountOnFiber (react-dom.development.js:24926:13)
at commitPassiveMountEffects_complete (react-dom.development.js:24891:9)
at commitPassiveMountEffects_begin (react-dom.development.js:24878:7)
at commitPassiveMountEffects (react-dom.development.js:24866:3)
Here is the code:
The create API endpoint:
import { createApi, fetchBaseQuery } from '#reduxjs/toolkit/dist/query/react';
export const widgetConfigApi = createApi( {
reducerPath: 'widgetconfig',
baseQuery: fetchBaseQuery( { baseUrl: '/' } ),
endpoints: ( builder ) => ( {
widgetConfig: builder.query<any[], void>( {
query: () => 'widgetconfig.json',
} ),
} ),
} );
export const { useWidgetConfigQuery } = widgetConfigApi;
The store:
const store = configureStore( {
reducer: {
widgets,
[ widgetConfigApi.reducerPath ]: widgetConfigApi.reducer
},
middleware: ( getDefaultMiddleware ) => getDefaultMiddleware().concat( widgetConfigApi.middleware ),
enhancers: composeEnhancers,
} );
And inside the component I am using the hook:
import { Layout, theme } from 'antd';
import React, { useEffect, useState, lazy } from 'react';
import { v4 } from 'uuid';
import './assets/styles/main.css';
import lineChart from './components/mock/chart-data/lineChart';
import { sideMenuItems } from './components/mock/side-menu/items';
import SideMenu from './components/side-menu/SideMenu';
import { Widget } from '#babilon/babilon-ui-components';
import { useWidgetConfigQuery } from './redux/api/widgetApi';
function App () {
const { Header, Content, Footer } = Layout;
const {
token: { colorBgLayout },
} = theme.useToken();
const [ widgetConfig, setWidgetConfig ] = useState( [] );
const { data, isLoading } = useWidgetConfigQuery();
useEffect( () => {
console.log( data );
!isLoading && setWidgetConfig( data );
}, [] );
return (
<Layout style={ { height: '100vh' } }>
<SideMenu items={ sideMenuItems } />
<Layout style={ { overflow: 'auto', position: 'relative' } }>
<Header style={ { padding: 0, background: colorBgLayout } } />
<Content style={ { margin: '0 16px' } }>
{ widgetConfig.map( ( config: any ) => {
const X = lazy( () => import( config.path ) );
const Y = lazy( () => import( config?.drawer.path ) );
return (
<React.Suspense key={ config.id }>
<Widget styles={ { height: 350 } } className="h-350" { ...structuredClone( config ) } uuid={ v4() }>
<X content series={ lineChart.series } />
</Widget>
</React.Suspense> );
} ) }
</Content>
<Footer style={ { textAlign: 'center' } }>Ant Design ©2018 Created by Ant UED</Footer>
</Layout>
</Layout>
);
}
export default App;
Just for context, I am using vite.
I don't know what am I doing wrong here. I checked the docs like 10 times. The ApiProvider works but it should work with the default provider as well.
Update:
I started a new clean project. In vite+react and in create-react-app version of the project I have the same error.
Here is a condesanbox to try and tinker. Maybe I am setting this poorly.
Sandbox

The problem are the enhancers: composeEnhancers.
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
The configureStore function enables the redux dev tools by itself and it's a bad match with the RTK Query package.
import { configureStore } from "#reduxjs/toolkit";
import { API } from "./api";
export const store = configureStore( {
reducer: {
[ API.reducerPath ]: API.reducer
},
middleware: ( getDefaultMiddleware ) => getDefaultMiddleware().concat( API.middleware ),
} );
store.dispatch;
Here is the sample code of the updated store. The codesandbox is updated as well.

Related

Deploying react app using fabricjs causing error in functionality

I'm trying to deploy a React app using fabricjs. On localhost it's working fine but after deploying , fabric functions not working and causing an error
Uncaught TypeError: Cannot read properties of null (reading 'add')
what can be the issue ? and if anyone know it what can be the possible solution ?
here is the code for adding text box to the fabric canvas
import { fabric } from 'fabric';
import ContextCanvas from '../../../context/ContextCanvas';
import { Button } from '#chakra-ui/react';
const FabricTextBox = () => {
const [canvas] = useContext(ContextCanvas);
function addTextBox() {
const textbox = new fabric.Textbox('Click on the Rectangle to move it.', {
fontSize: 20,
left: 50,
top: 100,
width: 200,
fill: 'black',
color: 'white',
cornerColor: 'blue',
});
canvas.add(textbox);
canvas.requestRenderAll();
}
return (
<>
<Button
type="button"
colorScheme="blue"
onClick={addTextBox}
variant={'ghost'}
_hover={{}}
_focus={{}}
_active={{}}
textColor={'white'}
fontWeight={'light'}
>
Text Field
</Button>
</>
);
};
export default FabricTextBox;
here is my fabric canvas
import React, { useContext, useLayoutEffect } from 'react';
import { fabric } from 'fabric';
import ContextCanvas from '../../context/ContextCanvas';
const FabricCanvas = () => {
const [canvas, initCanvas] = useContext(ContextCanvas);
useLayoutEffect(() => {
return () => {
initCanvas(new fabric.Canvas('c'));
};
}, []);
return (
<>
<canvas
id="c"
width={window.innerWidth}
height={window.innerHeight}
/>
</>
)
}
export default FabricCanvas;
here is my context provider
import { fabric } from 'fabric';
const ContextCanvas = createContext();
export function CanvasProvider({ children }) {
const [canvas, setCanvas] = useState(null);
const initCanvas = c => {
setCanvas(c);
c.renderAll();
};
return (
<ContextCanvas.Provider value={[canvas, initCanvas]}>
{children}
</ContextCanvas.Provider>
);
}
export default ContextCanvas;

Nothing was returned from render in react functional component

I am working with react to fetch data from the node backend and implement the UI with the data. I rendered the UI conditionally but I do get an error in the console saying that nothing was returned from render. Here is my code
import React, { useEffect, useState } from "react";
import OT from "#opentok/client";
import { OTSession, OTPublisher, OTStreams, getPublisher } from "opentok-react";
import Connection from "./Connection";
import Publisher from "./Publisher";
import Subscriber from "./Subscriber";
import { useParams } from "react-router-dom";
import { connect } from "react-redux";
import { Creators } from "../../../services/redux/event/actions";
import { PropTypes } from "prop-types";
import { makeStyles, Container } from "#material-ui/core";
function Host(props) {
const [connect, setConnect] = useState(false);
const params = useParams();
const { event, error, isCreatingEvent } = props;
console.log(event, "event");
const handleSessionOn = () => {
setConnect(true);
};
useEffect(() => {
props.getSingle(params.id);
}, []);
if (isCreatingEvent) {
return <div>Loading .....</div>;
}
if (error) {
return <div>Error: {error.error_message}</div>;
}
if (event.sessionId != undefined) {
const { API_KEY: apiKey, sessionId, token } = event;
console.log(apiKey, sessionId, token)
return (
<div style={{ zIndex: 100 }}>
<Connection connect={connect} />
<h3 style={{ color: "red" }}>This is apiKey connect</h3>
<OTSession
sessionId={sessionId}
token={token}
apiKey={apiKey}
onConnect={handleSessionOn}
>
<Publisher />
<OTStreams>
<Subscriber sessionId={sessionId} />
</OTStreams>
</OTSession>
</div>
)
}
}
Host.protoTypes = {
event: PropTypes.object.isRequired,
error: PropTypes.string,
};
const mapDispatchToProps = (dispatch) => {
return {
getSingle: (id) => {
dispatch(Creators.getOneEvent(id));
},
};
};
const mapStateToProps = (state) => (
console.log(state),
{
event: state.event.event,
error: state.event.error,
isCreatingEvent: state.event.isCreatingEvent,
}
);
export default connect(mapStateToProps, mapDispatchToProps)(Host);
Can anyone please help me out? I used the redux state to connect with Vonage API but the OTSession is not being rendered.
You called the return function only on the if statement.
You should call the return function on the else statement.
Like this.
const { API_KEY: apiKey, sessionId, token } = event;
{event.sessionId != undefined ? (
<div style={{ zIndex: 100 }}>
<Connection connect={connect} />
<h3 style={{ color: "red" }}>This is apiKey connect</h3>
<OTSession
sessionId={sessionId}
token={token}
apiKey={apiKey}
onConnect={handleSessionOn}
>
<Publisher />
<OTStreams>
<Subscriber sessionId={sessionId} />
</OTStreams>
</OTSession>
</div>
) : null}

Can't access state using 'useStoreState in react easy-peasy

I recently decided to learn about state management with easy-peasy, and followed along the basic tutorials, but i can't seem to access the state.
Here is the App component :-
import model from './model';
import Todo from './components/Todo.tsx';
import { StoreProvider, createStore } from 'easy-peasy';
const store = createStore(model);
function App() {
return (
<StoreProvider store={store}>
<div className="App">
<Todo />
</div>
</StoreProvider>
);
}
export default App;
Here is the model file 'model.js'
export default {
todos: [
{
id: 1
},
{
id: 2
},
{
id: 3
}
]
};
And this is the Todo file:-
import React from 'react';
import {useStoreState } from 'easy-peasy';
const Todo = () => {
//The line below does not work for me, when i do 'state.todos' i get an error that todos does not exist on type
const todos = useStoreState(state=>state.todos);
return (
<div>
</div>
);
}
export default Todo;
Try removing the .todos so that
const todos = useStoreState(state=>state.todos);
turns into:
const todos = useStoreState(state=>state);
import React from 'react'
import { useStoreState } from 'easy-peasy';
import Feed from './Feed'
const Home = ({isLoading,fetchError}) => {
const { searchResults} = useStoreState((state)=>state.searchResults)
return (
{isLoading && Loading Posts ...};
{fetchError && <p className='statusMsg' style={{ color: "red" }}>{ fetchError }};
{!isLoading && !fetchError && (searchResults.length ? : No posts to display)}
)
}
export default Home;

Having React Context in Separate File, Can't Get Component to Not re-render

I've got a simple example of React Context that uses useMemo to memoize a function and all child components re-render when any are clicked. I've tried several alternatives (commented out) and none work. Please see code at stackblitz and below.
https://stackblitz.com/edit/react-yo4eth
Index.js
import React from "react";
import { render } from "react-dom";
import Hello from "./Hello";
import { GlobalProvider } from "./GlobalState";
function App() {
return (
<GlobalProvider>
<Hello />
</GlobalProvider>
);
}
render(<App />, document.getElementById("root"));
GlobalState.js
import React, {
createContext,useState,useCallback,useMemo
} from "react";
export const GlobalContext = createContext({});
export const GlobalProvider = ({ children }) => {
const [speakerList, setSpeakerList] = useState([
{ name: "Crockford", id: 101, favorite: true },
{ name: "Gupta", id: 102, favorite: false },
{ name: "Ailes", id: 103, favorite: true },
]);
const clickFunction = useCallback((speakerIdClicked) => {
setSpeakerList((currentState) => {
return currentState.map((rec) => {
if (rec.id === speakerIdClicked) {
return { ...rec, favorite: !rec.favorite };
}
return rec;
});
});
},[]);
// const provider = useMemo(() => {
// return { clickFunction: clickFunction, speakerList: speakerList };
// }, []);
//const provider = { clickFunction: clickFunction, speakerList: speakerList };
const provider = {
clickFunction: useMemo(() => clickFunction,[]),
speakerList: speakerList,
};
return (
<GlobalContext.Provider value={provider}>{children}</GlobalContext.Provider>
);
};
Hello.js
import React, {useContext} from "react";
import Speaker from "./Speaker";
import { GlobalContext } from './GlobalState';
export default () => {
const { speakerList } = useContext(GlobalContext);
return (
<div>
{speakerList.map((rec) => {
return <Speaker speaker={rec} key={rec.id}></Speaker>;
})}
</div>
);
};
Speaker.js
import React, { useContext } from "react";
import { GlobalContext } from "./GlobalState";
export default React.memo(({ speaker }) => {
console.log(`speaker ${speaker.id} ${speaker.name} ${speaker.favorite}`);
const { clickFunction } = useContext(GlobalContext);
return (
<>
<button
onClick={() => {
clickFunction(speaker.id);
}}
>
{speaker.name} {speaker.id}{" "}
{speaker.favorite === true ? "true" : "false"}
</button>
</>
);
});
Couple of problems in your code:
You already have memoized the clickFunction with useCallback, no need to use useMemo hook.
You are consuming the Context in Speaker component. That is what's causing the re-render of all the instances of Speaker component.
Solution:
Since you don't want to pass clickFunction as a prop from Hello component to Speaker component and want to access clickFunction directly in Speaker component, you can create a separate Context for clickFunction.
This will work because extracting clickFunction in a separate Context will allow Speaker component to not consume GlobalContext. When any button is clicked, GlobalContext will be updated, leading to the re-render of all the components consuming the GlobalContext. Since, Speaker component is consuming a separate context that is not updated, it will prevent all instances of Speaker component from re-rendering when any button is clicked.
Demo
const GlobalContext = React.createContext({});
const GlobalProvider = ({ children }) => {
const [speakerList, setSpeakerList] = React.useState([
{ name: "Crockford", id: 101, favorite: true },
{ name: "Gupta", id: 102, favorite: false },
{ name: "Ailes", id: 103, favorite: true }
]);
return (
<GlobalContext.Provider value={{ speakerList, setSpeakerList }}>
{children}
</GlobalContext.Provider>
);
};
const ClickFuncContext = React.createContext();
const ClickFuncProvider = ({ children }) => {
const { speakerList, setSpeakerList } = React.useContext(GlobalContext);
const clickFunction = React.useCallback(speakerIdClicked => {
setSpeakerList(currentState => {
return currentState.map(rec => {
if (rec.id === speakerIdClicked) {
return { ...rec, favorite: !rec.favorite };
}
return rec;
});
});
}, []);
return (
<ClickFuncContext.Provider value={clickFunction}>
{children}
</ClickFuncContext.Provider>
);
};
const Speaker = React.memo(({ speaker }) => {
console.log(`speaker ${speaker.id} ${speaker.name} ${speaker.favorite}`);
const clickFunction = React.useContext(ClickFuncContext)
return (
<div>
<button
onClick={() => {
clickFunction(speaker.id);
}}
>
{speaker.name} {speaker.id}{" "}
{speaker.favorite === true ? "true" : "false"}
</button>
</div>
);
});
function SpeakerList() {
const { speakerList } = React.useContext(GlobalContext);
return (
<div>
{speakerList.map(rec => {
return (
<Speaker speaker={rec} key={rec.id} />
);
})}
</div>
);
};
function App() {
return (
<GlobalProvider>
<ClickFuncProvider>
<SpeakerList />
</ClickFuncProvider>
</GlobalProvider>
);
}
ReactDOM.render(<App />, document.getElementById("root"));
<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>
<div id="root"></div>
You can also see this demo on StackBlitz
this will not work if you access clickFuntion in children from provider because every time you updating state, provider Object will be recreated and if you wrap this object in useMemolike this:
const provider = useMemo(()=>({
clickFunction,
speakerList,
}),[speakerList])
it will be recreated each time clickFunction is fired.
instead you need to pass it as prop to the children like this:
import React, {useContext} from "react";
import Speaker from "./Speaker";
import { GlobalContext } from './GlobalState';
export default () => {
const { speakerList,clickFunction } = useContext(GlobalContext);
return (
<div>
{speakerList.map((rec) => {
return <Speaker speaker={rec} key={rec.id} clickFunction={clickFunction }></Speaker>;
})}
</div>
);
};
and for provider object no need to add useMemo to the function clickFunction it's already wrapped in useCallback equivalent to useMemo(()=>fn,[]):
const provider = {
clickFunction,
speakerList,
}
and for speaker component you don't need global context :
import React from "react";
export default React.memo(({ speaker,clickFunction }) => {
console.log("render")
return (
<>
<button
onClick={() => {
clickFunction(speaker.id);
}}
>
{speaker.name} {speaker.id}{" "}
{speaker.favorite === true ? "true" : "false"}
</button>
</>
);
});

Redux loses state when navigating to another page in Next.js

I'm creating the redux state in this page :
import React from 'react';
import { connect } from 'react-redux';
import styled from 'styled-components';
import wrapper from '../redux/store';
import Container from '../components/Container/Container';
import Card from '../components/Card/Card';
import Circle from '../components/Circle/Circle';
import PieChart from '../components/PieChart/PieChart';
import Accordion from '../components/Accordion/Accordion';
import RadioButton from '../components/Ui/RadioButton/RadioButton';
import { manageList, reportList } from '../components/helper';
import { getManageListAndCategoryId } from '../redux/actions/actions';
const Panel = ({ manageProductsList }) => (
<>
{console.log(manageProductsList)}
<MainContainer>
<Title>Управление</Title>
<ContainersWrapper>
{manageProductsList.map((item, index) => <Card key={index} title={item.title} type="service" serviceName={item.value} />)}
</ContainersWrapper>
<SecondSection>
<CustomContainer>
<Title>Отчетность</Title>
<p>Показатели за:</p>
Здесь будут ТАБЫ
<ContainersWrapper>
{reportList.map((item, index) => <Card key={index} item={item} type="report" />)}
</ContainersWrapper>
<DiagreammWrapper>
<PieChart />
<Circle percent={20} />
<Circle percent={87} />
<Circle percent={30} />
<Circle percent={47} />
</DiagreammWrapper>
</CustomContainer>
</SecondSection>
<CustomContainer>
<TitleTwo>Доступные отчеты</TitleTwo>
<Accordion />
<RadioButton />
</CustomContainer>
</MainContainer>
</>
);
export const getStaticProps = wrapper.getStaticProps(async ({ store }) => {
store.dispatch(getManageListAndCategoryId(manageList));
});
const mapStateToProps = (state) => ({
manageProductsList: state.mainReducer.manageProductsList,
});
export default connect(mapStateToProps, null)(Panel);
And I still can see the data manageProductsList (screenshot) in Redux in this page. But when I navigate to another dynamic route page forms/[id.tsx]
import React from 'react';
import { connect } from 'react-redux';
import wrapper from '../redux/store';
import { util, manageList, reportList } from '../../components/helper';
import { getManageListAndCategoryId } from '../../redux/actions/actions';
export async function getStaticPaths(categoryIds) {
console.log('categoryIds', categoryIds);
//temporarely make static path data while categoryIds is undefined
const paths = [
{ params: { id: 'object' } },
{ params: { id: 'service' } },
{ params: { id: 'club_cards' } },
{ params: { id: 'schedule' } },
{ params: { id: 'agents' } },
{ params: { id: 'abonements' } },
{ params: { id: 'price_category' } },
{ params: { id: 'person_data' } },
{ params: { id: 'roles' } },
];
return {
paths,
fallback: false,
};
}
export async function getStaticProps({ params, manageProductsList }) {
// const postData = util.findFormData(params.id, manageProductsList);
const postData = { title: 'asdsadasdsad' };
return {
props: {
postData,
},
};
}
const Form = ({ manageProductsList }) => (
<div>
{console.log(manageProductsList)}
{/* {postData.title} */}
dasdsadsad
</div>
);
const mapStateToProps = (state) => ({
categoryIds: state.mainReducer.categoryIds,
manageProductsList: state.mainReducer.manageProductsList,
});
export default connect(mapStateToProps, null)(Form);
the manageProductsList and categoryIds are empty arrays (screenshot 2)
I am using native Link from next/link component to navigate the page
Here is Card component which navigate to dynamic page:
import React, { FunctionComponent, HTMLAttributes } from 'react';
import styled from 'styled-components';
import Link from 'next/link';
import EditIcon from '#material-ui/icons/Edit';
import AddIcon from '#material-ui/icons/Add';
interface CardProps extends HTMLAttributes<HTMLOrSVGElement>{
title: string
type: string
item?: {
title: string
amount: number
}
serviceName: string
}
const Card: FunctionComponent<CardProps> = ({
type, title, serviceName, item,
}) => (
<>
{
type === 'service'
&& (
<FirstSection>
<h1>{title}</h1>
<ImageWrapper>
<Link href={`/forms/${serviceName}`}>
<a><AddIcon fontSize="large" onClick={(e) => { console.log(serviceName); }} /></a>
</Link>
<EditIcon />
</ImageWrapper>
</FirstSection>
)
}
{
type === 'report'
&& (
<SecondSection>
<h1>{item.title}</h1>
<p>{item.amount}</p>
</SecondSection>
)
}
</>
);
export default Card;
I would be very gratefull if someone can help
Your <Link> will cause server-side rendering, you can observe whether the browser tab is loading or not when navigate to another page. If it is, the page will reload and the redux state would be refresh.
The official docs shows the right way for using dynamic route.
<Link href="/forms/[id]" as={`/forms/${serviceName}`}>

Resources