I would like to open and close an antd Modal component using a MobX store. I have the following code Here's a link to codesandbox https://codesandbox.io/s/nifty-dijkstra-g0kzs6?file=/src/App.js
import AppNavigation from "./components/Menu";
import ContactPopUp from "./components/Contact";
export default function App() {
return (
<div className="App">
<AppNavigation />
<ContactPopUp />
</div>
);
}
File with the MobXstore
import { createContext, useContext } from "react";
import AppStore from "./appStore";
interface Store {
appStore: AppStore;
}
export const store: Store = {
appStore: new AppStore()
};
export const StoreContext = createContext(store);
export function useStore() {
return useContext(StoreContext);
}
Separate file where I declare the store
import { makeAutoObservable } from "mobx";
export default class AppStore {
contactFormOpen = false;
constructor() {
makeAutoObservable(this);
}
setContactFormOpen = (isOpen: boolean) => {
console.log("Changed contact form to ", isOpen);
this.contactFormOpen = isOpen;
};
}
The Menu.tsx
import React from "react";
import { Menu, MenuProps } from "antd";
import { useStore } from "../store/store";
const AppNavigation = () => {
const { appStore } = useStore();
const menuItems: MenuProps["items"] = [
{
label: <a onClick={(e) => handleOpenContactForm(e)}>Contact</a>,
key: "Contact"
}
];
const handleOpenContactForm = (e: any) => {
e.preventDefault();
e.stopPropagation();
appStore.setContactFormOpen(true);
console.log("Open contact pop up", appStore.contactFormOpen);
};
return (
<Menu
items={menuItems}
theme="dark"
overflowedIndicator={""}
className="header__menu award-menu header__menu--md"
/>
);
};
export default AppNavigation;
ContactPopUp.tsx
import { Modal } from "antd";
import React, { useEffect, useState } from "react";
import { useStore } from "../store/store";
const ContactPopUp = () => {
const { appStore } = useStore();
const [visible, setVisible] = useState(appStore.contactFormOpen);
useEffect(() => {
setVisible(appStore.contactFormOpen);
}, [appStore.contactFormOpen]);
const handleCancel = () => {
appStore.setContactFormOpen(false);
console.log("Close contact from", appStore.contactFormOpen);
};
return (
<Modal title="Contact us" visible={visible} onCancel={handleCancel}>
<h2>Modal Open</h2>
</Modal>
);
};
export default ContactPopUp;
The mobx contactFormOpen clearly changes but the modal state does not. I really don't understand why... UseEffect also doesn't trigger a re render.
You just forgot most crucial part - every component that uses any observable value needs to be wrapped with observer decorator! Like that:
const ContactPopUp = () => {
const { appStore } = useStore();
const handleCancel = () => {
appStore.setContactFormOpen(false);
console.log('Close contact from', appStore.contactFormOpen);
};
return (
<Modal
title="Contact us"
visible={appStore.contactFormOpen}
onCancel={handleCancel}
>
<h2>Modal Open</h2>
</Modal>
);
};
// Here I've added `observer` decorator/HOC
export default observer(ContactPopUp);
And you don't need useEffect or anything like that now.
Codesandbox
Related
I want to know if is possible to navigate between screens, using like a context api, or something else, where I can get the "navigateTo" function in any component without passing by props. And of course, without the cycle dependency problem.
Example with the cycle dependency problem
NavigateContext.tsx:
import React, { createContext, useMemo, useReducer } from 'react'
import { Home } from './pages/Home'
interface NavigateProps {
navigateTo: (screenName: string) => void
}
export const navigateContext = createContext({} as NavigateProps)
const reducer = (state: () => JSX.Element, action: { type: string }) => {
switch (action.type) {
case 'home':
return Home
default:
throw new Error('Page not found')
}
}
export function NavigateContextProvider() {
const [Screen, dispatch] = useReducer(reducer, Home)
const value = useMemo(() => {
return {
navigateTo: (screenName: string) => {
dispatch({ type: screenName })
},
}
}, [])
return (
<navigateContext.Provider value={value}>
<Screen />
</navigateContext.Provider>
)
}
Home.tsx:
import React, { useContext, useEffect } from 'react'
import { Flex, Text } from '#chakra-ui/react'
import { navigateContext } from '../NavigateContext'
export function Home() {
const { navigateTo } = useContext(navigateContext)
useEffect(() => {
setTimeout(() => {
navigateTo('home')
}, 2000)
}, [])
return (
<Flex>
<Text>Home</Text>
</Flex>
)
}
Yes, this is possible, but you'll need to maintain the list of string view names independently from your mapping of them to their associated components in order to avoid circular dependencies (what you call "the cycle dependency problem" in your question):
Note, I created this in the TS Playground (which doesn't support modules AFAIK), so I annotated module names in comments. You can separate them into individual files to test/experiment.
TS Playground
import {
default as React,
createContext,
useContext,
useEffect,
useState,
type Dispatch,
type ReactElement,
type SetStateAction,
} from 'react';
////////// views.ts
// Every time you add/remove a view in your app, you'll need to update this array:
export const views = ['home', 'about'] as const;
export type View = typeof views[number];
export type ViewContext = {
setView: Dispatch<SetStateAction<View>>;
};
export const viewContext = createContext({} as ViewContext);
////////// Home.ts
// import { viewContext } from './views';
export function Home (): ReactElement {
const {setView} = useContext(viewContext);
useEffect(() => void setTimeout(() => setView('home'), 2000), []);
return (<div>Home</div>);
}
////////// About.ts
// import { viewContext } from './views';
export function About (): ReactElement {
const {setView} = useContext(viewContext);
return (
<div>
<div>About</div>
<button onClick={() => setView('home')}>Go Home</button>
</div>
);
}
////////// ContextProvider.tsx
// import {viewContext, type View} from './views';
// import {Home} from './Home';
// import {About} from './About';
// import {Etc} from './Etc';
// Every time you add/remove a view in your app, you'll need to update this object:
const viewMap: Record<View, () => ReactElement> = {
home: Home,
about: About,
// etc: Etc,
};
function ViewProvider () {
const [view, setView] = useState<View>('home');
const CurrentView = viewMap[view];
return (
<viewContext.Provider value={{setView}}>
<CurrentView />
</viewContext.Provider>
);
}
How to link react with redux to add and remove selected movies to the array by clicking on the heart to display them on the favoгites page
Bellow my redux:
action:
export function addMovie(id) {
return {
type: 'ADD_MOVIE',
payload: id
}
}
export function removeMovie(id) {
return {
type: 'REMOVE_MOVIE',
payload: id
}
}
reducer:
function favouriteReducer(state = [], action) {
switch(action.type) {
case 'ADD_MOVIE':
return {
items: state.items.concat(action.payload)
}
case 'REMOVE_MOVIE':
return {
items: state.items.filter(item => item !== action.payload)
}
default:
return state;
}
}
export default favouriteReducer;
store:
import { createStore, combineReducers, applyMiddleware } from 'redux';
import { composeWithDevTools } from "redux-devtools-extension";
import thunk from "redux-thunk";
import favouriteReducer from "./reducers/favouriteReducer";
const redusers = combineReducers({
favourite: favouriteReducer,
});
const store = createStore(redusers, composeWithDevTools(applyMiddleware(thunk)));
export default store;
and my component, where i need to click to add or remove chosen movie
import React, { useEffect, useState } from "react";
import './index.css';
import { Link, useParams } from "react-router-dom";
import { connect } from 'react-redux';
import { addMovie } from "../../../../redux/actions/favouriteMovie";
import store from "../../../../redux";
const MoviesContext = React.createContext();
const { Provider } = MoviesContext;
const Movie = (props, {addMovie, movies}) => {
const [active, setActive] = useState(false)
let onClick = (e) => {
e.preventDefault();
console.log('hello');
setActive(!active);
addMovie(movies);
}
return (
<Provider store={{movies, addMovie}}>
<Link to= {"/modal/:"+`${props.id}`} id={props.id} className={'movie'}>
<img src={"https://image.tmdb.org/t/p/w500/"+props.poster_path} alt={props.title} className={'main'}/>
<h1 className={'title'}>{props.title}</h1>
<div>
<svg className={active ? 'activeimg' : 'heart'} onClick={onClick} xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M12 4.248c-3.148-5.402-12-3.825-12 2.944 0 4.661 5.571 9.427 12 15.808 6.43-6.381 12-11.147 12-15.808 0-6.792-8.875-8.306-12-2.944z"/></svg>
<p className={'text'}>{props.release_date}</p>
</div>
</Link>
</Provider>
);
};
export {
MoviesContext
};
function mapStateToProps(state){
return {
movies: state.movie.movies
}
}
const mapDispatchToProps = {
addMovie: addMovie,
}
export default connect(mapStateToProps, mapDispatchToProps)(Movie);
I don't understand how to do it in component.
Thank you very much for your help!
You need to change your "mapDispatchToProps" to have a dispatch as params
but why this mixt between context and redux ?
import React, { useEffect, useState } from 'react';
import './index.css';
import { Link, useParams } from 'react-router-dom';
import { connect } from 'react-redux';
import { addMovie } from '../../../../redux/actions/favouriteMovie';
import store from '../../../../redux';
const MoviesContext = React.createContext();
const { Provider } = MoviesContext;
const Movie = (props, { addMovie, movies }) => {
const [active, setActive] = useState(false);
const onClick = (id) => {
console.log('hello');
setActive(!active);
props.addMovie(id);
};
return (
<Provider store={{ movies, addMovie }}>
<Link to={'/modal/:' + `${props.id}`} id={props.id} className={'movie'}>
<img src={'https://image.tmdb.org/t/p/w500/' + props.poster_path} alt={props.title} className={'main'} />
<h1 className={'title'}>{props.title}</h1>
<div>
<svg className={active ? 'activeimg' : 'heart'} onClick={() => onClick(props.id)} xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
<path d="M12 4.248c-3.148-5.402-12-3.825-12 2.944 0 4.661 5.571 9.427 12 15.808 6.43-6.381 12-11.147 12-15.808 0-6.792-8.875-8.306-12-2.944z" />
</svg>
<p className={'text'}>{props.release_date}</p>
</div>
</Link>
</Provider>
);
};
export { MoviesContext };
function mapStateToProps(state) {
return {
movies: state.movie.movies,
};
}
const mapDispatchToProps = {
addMovie: addMovie,
};
const mapDispatchToProps = (dispatch) => {
return {
addMovie: (id) => dispatch(addMovie(id)),
};
};
export default connect(mapStateToProps, mapDispatchToProps)(Movie);
How to pass text value to another component using Redux in React?
I am learning Redux in React. I am trying to pass text value to another component using Redux in React.
My code is like below
Mycomponent.js
import React, { Component } from 'react';
import { connect } from 'react-redux';
class Mycomponent extends Component {
state = {
textInput: '',
}
handleChange = event => {
this.props.dispatch({ type: "add" });
}
render = () => {
return (
<div>
<input
type="text"
onChange={this.handleChange} />
</div>
);
}
}
const mapStateToProps = state => ({ nameState: state.nameState});
export default connect(mapStateToProps)(Mycomponent);
nameAction.js
export const nameAction = () => ({
type: 'add'
});
export default { nameAction };
nameReducer.js
const nameReducer = (state = {}, action) => {
switch (action.type) {
case 'add': {
return {
...state,
nameState: action.payload
};
}
default:
return state;
}
};
export default nameReducer;
Outputcomponent.js
import React, { Component } from 'react';
class Outputcomponent extends Component {
render = (props) => {
return (
<div>
<div>{this.props.nameState }</div>
</div>
);
}
}
export default Outputcomponent;
The use of redux hooks explained by Josiah is for me the best approach but you can also use mapDispatchToProps.
Even if the main problem is that you don't pass any data in your 'add' action.
nameAction.js
You call the action.payload in nameReducer.js but it does not appear in your action
export const nameAction = (text) => ({
type: 'add',
payload: text
});
Mycomponent.js
Then as for your state we can mapDispatchToProps.
(I think it's better to trigger the action with a submit button and save the input change in your textInput state, but I guess it's intentional that there is none)
import React, { Component } from 'react';
import { connect } from 'react-redux';
import {nameAction} from './nameAction'
class Mycomponent extends Component {
state = {
textInput: '',
}
handleChange = event => {
this.props.nameAction(event.target.value);
}
render = () => {
return (
<div>
<input
type="text"
onChange={this.handleChange} />
</div>
);
}
}
const mapStateToProps = state => ({ nameState: state.nameState});
const mapDispatchToProps = dispatch => ({ nameAction: (text) => dispatch(nameAction(text))});
export default connect(mapStateToProps,mapDispatchToProps)(Mycomponent);
OutputComponent.js
to get the data two possibilities either with a class using connect and mapStateToProps , or using the useSelector hook with a functional component.
with a Class
import React, { Component } from "react";
import { connect } from "react-redux";
class OutputComponent extends Component {
render = () => {
return (
<div>
<div>{this.props.nameState}</div>
</div>
);
};
}
const mapStateToProps = state => state;
export default connect(mapStateToProps)(OutputComponent);
with a functional component
import React from "react";
import { useSelector } from "react-redux";
const OutputComponent = () => {
const nameState = useSelector((state) => state.nameState);
return (
<div>
<div>{nameState}</div>
</div>
);
};
export default OutputComponent;
Of course you must not forget to create a strore and to provide it to the highest component
store.js
import { createStore } from "redux";
import nameReducer from "./nameReducer";
const store = createStore(nameReducer);
export default store;
index.js
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
import { Provider } from "react-redux";
import store from "./store";
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById("root")
);
Component
const AddTodo = () => {
const [todo, setTodo] = useState("");
const dispatch = useDispatch();
const handleChange = (e) => setTodo(e.target.value);
const handleSubmit = (e) => {
e.preventDefault();
dispatch(addTodoAction(todo));
}
return {
<form onSubmit={handleSubmit}>
<input type="text" onChange={handleChange} />
</form>
}
)
Actions
const addTodoAction = (text) => {
dispatch({
type: "ADD_TODO",
payload: text
})
}
Reducers
const addTodoReducer = (state, action) => {
switch(action.type) {
case "ADD_TODO":
return {
todo: action.payload,
}
default:
return state;
}
}
store
// some code for store.js
Accessing this todo from another component
const ComponentA = () => {
const {todo} = useSelector(state => state.todo);
return (
<p> {todo} </p>
)
}
Side Note:
Redux comes with too much boilerplate if you want to pass text from one component to another, just use props
I can't seem to find a way to set initial checkbox state from MobX store after a fast refresh from Next.js. As soon as i refresh the page, it renders with the state i set before.
For example: i check the checkbox (which has the checked/onChange routed to MobX) -> Page refresh -> The input persists to be checked, while the state is set to false.
I've tried all the other ways to pass the observer HOC (Observer, useObserver), disabling hydration, reworking store, but to no avail.
Here's the code:
store/ThemeStore.ts
import { makeAutoObservable } from 'mobx';
export type ThemeHydration = {
darkTheme: boolean;
};
class ThemeStore {
darkTheme = false;
constructor() {
makeAutoObservable(this);
}
setDarkTheme(value: boolean) {
this.darkTheme = value;
}
hydrate(data?: ThemeHydration) {
if (data) {
this.darkTheme = data.darkTheme;
}
}
}
export default ThemeStore;
pages/index.tsx
import React, { useEffect } from "react";
import { reaction } from "mobx";
import styles from "#/styles/homepage.module.scss";
import { observer } from "mobx-react";
import { useStore } from "#/stores";
const HomePage = observer(function () {
const { themeStore } = useStore();
useEffect(() => {
const re = reaction(
() => themeStore.darkTheme,
(value) => {
const body = document.body;
if (value) {
body.classList.remove("theme-light");
body.classList.add("theme-dark");
} else {
body.classList.remove("theme-dark");
body.classList.add("theme-light");
}
},
{ fireImmediately: true }
);
return () => {
re();
};
}, []);
return (
<div className={styles.container}>
<main className={styles.main}>
<input
type="checkbox"
defaultChecked={themeStore.darkTheme}
onChange={(e) => {
themeStore.setDarkTheme(e.target.checked);
}}
/>
</main>
</div>
);
});
export default HomePage;
stores/index.tsx
import React, { ReactNode, createContext, useContext } from "react";
import { enableStaticRendering } from "mobx-react";
import RootStore, { RootStoreHydration } from "./RootStore";
enableStaticRendering(typeof window === "undefined");
export let rootStore = new RootStore();
export const StoreContext = createContext<RootStore | undefined>(undefined);
export const useStore = () => {
const context = useContext(StoreContext);
if (context === undefined) {
throw new Error("useRootStore must be used within RootStoreProvider");
}
return context;
};
function initializeStore(initialData?: RootStoreHydration): RootStore {
const _store = rootStore ?? new RootStore();
if (initialData) {
_store.hydrate(initialData);
}
// For SSG and SSR always create a new store
if (typeof window === "undefined") return _store;
// Create the store once in the client
if (!rootStore) rootStore = _store;
return _store;
}
export function RootStoreProvider({
children,
hydrationData,
}: {
children: ReactNode;
hydrationData?: RootStoreHydration;
}) {
const store = initializeStore(hydrationData);
return (
<StoreContext.Provider value={store}>{children}</StoreContext.Provider>
);
}
Thanks in advance!
I have two distinct contexts in my application - Language and Currency. Each of these contexts are consumed by two distinct functional components through the useContext hook. When one of the context values change I want React to only invoke the functional component that consumes that context and not the other. However I find that both functional components get invoked when either context values change. How can I prevent this? Even if React doesn't re-render unchanged DOM after reconciliation I would like to prevent actually calling of the functional component itself.In other words how can I memoize each component (or something similar) while still maintaining my code organization (See below)?
LanguageContext.js
import React from 'react';
const LanguageContext = React.createContext({ lang: 'english', changeLang: (lang) => { } });
export { LanguageContext };
CurrencyContext.js
import React from 'react';
const CurrencyContext = React.createContext({ cur: '$', changeCur: (cur) => { } });
export { CurrencyContext };
ContextRoot.js
import React, { useState } from 'react';
import { LanguageContext } from '../context/LanguageContext';
import { CurrencyContext } from '../context/CurrencyContext';
const ContextRoot = (props) => {
const [lang, setLang] = useState('english');
const [cur, setCur] = useState('$');
const changeLang = (lang) => {
setLang(lang);
}
const changeCur = (cur) => {
setCur(cur);
}
const langCtx = {
lang,
changeLang
};
const curCtx = {
cur,
changeCur
};
return (
<LanguageContext.Provider value={langCtx}>
<CurrencyContext.Provider value={curCtx}>
{props.children}
</CurrencyContext.Provider>
</LanguageContext.Provider>
);
}
export { ContextRoot };
App.js
import React from 'react';
import { Header } from './Header';
import { Welcome } from './Welcome';
import { Currency } from './Currency';
import { ContextRoot } from './ContextRoot';
const App = (props) => {
return (
<ContextRoot>
<div>
<Header />
<Welcome />
<Currency />
</div>
</ContextRoot>
);
}
export { App };
Header.js
import React, { useContext } from 'react';
import { LanguageContext } from '../context/LanguageContext';
import { CurrencyContext } from '../context/CurrencyContext';
const Header = (props) => {
const { changeLang } = useContext(LanguageContext);
const { changeCur } = useContext(CurrencyContext);
const handleLangClick = (lang) => {
changeLang(lang);
};
const handleCurClick = (cur) => {
changeCur(cur);
};
return (
<div>
<h2>Select your language: <button onClick={e => handleLangClick('english')}>English </button> <button onClick={e => handleLangClick('spanish')}>Spanish</button></h2>
<h2>Select your Currency: <button onClick={e => handleCurClick('$')}>Dollars </button> <button onClick={e => handleCurClick('€')}>Euros</button></h2>
</div>
);
};
export { Header };
Welcome.js
import React, { useContext } from 'react';
import { LanguageContext } from '../context/LanguageContext';
const Welcome = (props) => {
console.log('welcome..');
const { lang } = useContext(LanguageContext);
return (
<div>
<h1>{lang === 'english' ? 'Welcome' : 'Bienvenidos'}</h1>
</div>
);
};
export { Welcome };
Currency.js
import React, { useContext } from 'react';
import { CurrencyContext } from '../context/CurrencyContext';
const Currency = () => {
console.log('currency..');
const { cur } = useContext(CurrencyContext);
return (
<h2>Your chosen currency: {cur}</h2>
)
}
export { Currency };
what you need is useMemo. It's pretty easy to implement, take a look in docs to apply your needs. Hope help you :)
https://reactjs.org/docs/hooks-reference.html#usememo