I am new to gatsby and hope you can all helt me.
I am getting a typeerror: dispatch is not a function message, and have stuggled with finding my typo for two days now. I am trying to make a cart and need to pass the product to a global state. It is only when I set in the dispatch in my handleClick function I seem to get the problem (function works with only a console.log and takes in the product fine)
This is my code. First the provider, then the layout and last the template that holds a single product:
const CartStateContext = createContext();
const CartDispatchContext = createContext();
const reducer = (state, action) => {
switch (action.type) {
case "ADD":
return [...state, action.item];
default:
throw new Error(`unknown action ${action.type}`);
}
};
export const CartProvider = ({ children }) => {
const [ state, dispatch ] = useReducer(reducer, [])
return (
<CartDispatchContext.Provider value={dispatch}>
<CartStateContext.Provider value={state}>
{children}
</CartStateContext.Provider>
</CartDispatchContext.Provider>
)
};
export const useCart = () => useContext(CartStateContext);
export const useDispatchCart = () => useContext(CartDispatchContext);
/* layout component */
import React, { useState } from 'react';
import Container from './Container';
import Footerone from './Footerone/Footerone';
import HeaderOne from './HeaderOne/HeaderOne';
import ShopHeaderOne from './ShopHeaderOne/ShopHeaderOne';
import { CartContext } from './CartContext';
import { CartProvider } from './Cart'
export default ({ children }) => {
const[cartVisible, setCartVisible] = useState(false);
const toggleCart = () => {
setCartVisible(!cartVisible)
};
return (
<Container>
<CartProvider>
<CartContext.Provider value={{ cartVisible, toggleCart}}>
<HeaderOne />
<ShopHeaderOne />
{ children }
<Footerone />
</CartContext.Provider>
</CartProvider>
</Container>
)
}
/* singleproduct */
import React from 'react'
import Layout from "../Components/Layout"
import './templates.scss'
import { useDispatchCart } from '../Components/Cart';
export default ( props ) => {
const product = props.pageContext
const dispatch = useDispatchCart();
const handleClick = (item) => {
dispatch({ type: "ADD", item })
}
console.log(product)
return (
<Layout>
<section className="single-grid">
<h1>{product.headline}</h1>
<img src={product.image.mediaItemUrl} alt={product.image.altText}/>
<p>{product.price}</p>
<button onClick={handleClick(product)}>Føj til kurv</button>
</section>
</Layout>
)
}
Have you tried binding directly the dispatch?
return (
<Layout>
<section className="single-grid">
<h1>{product.headline}</h1>
<img src={product.image.mediaItemUrl} alt={product.image.altText}/>
<p>{product.price}</p>
<button onClick={()=> dispatch({ type: "ADD", item })}>Føj til kurv</button>
</section>
</Layout>
)
If the issue persists, check the reducer in order to see if it's being set properly.
Related
I have a state that I want to make global so that I can use it across multiple different components
and I am trying to do this through using context.
So I have my initial Component which gets the data and sets the global state, the issue I am having is when I try to use this state in the other components it seems to be empty because I believe my GlobalContext varibale is not updating so will be empty when the other components try to use the state. I cannot seem to figure out what I am missing to ensure my global state and context are both updated so that I can use them across the different components that require the data as well.
Can anyone figure out where I should update my context as well as my state
Component that gets the data initially:
import React from "react";
import { useState, useEffect, useMemo, useContext } from "react";
import axios from "axios";
import { GlobalContext } from "./Store";
function Map() {
// ------- global state
const [activities, setActivities] = useContext(GlobalContext);
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
setActivitieData();
console.log("activities after useEffect", activities)
}, []);
const getActivityData = async () => {
console.log("calling")
const response = await axios.get(
"http://localhost:8800/api/"
);
return response.data;
};
const setActivitieData = async () => {
const activityData = await getActivityData();
setActivities(activityData);
console.log("Global activities state = ", activities);
};
return !isLoading ? (
<>
<MapComp
activityData={activities}
/>
</>
) : (
<div>
<p>Loading...</p>
</div>
);
}
export default Map;
GlobalStateStore component:
import React, {useState} from "react";
const initState = [];
export const GlobalContext = React.createContext();
const Store = ({children}) => {
const [activities, setActivities] = useState(initState);
return (
<GlobalContext.Provider value={[activities, setActivities]}>
{children}
</GlobalContext.Provider>
)
}
export default Store;
component I am trying to use the global state in but is empty:
import React, {useContext} from 'react';
import { GlobalContext } from "./Store";
function ActivityList() {
const [activities, setActivities] = useContext(GlobalContext);
let displayValues;
displayValues =
activities.map((activity) => {
return (
<div>
<p>{activity.name}</p>
<p>{activity.distance}m</p>
</div>
);
})
return (
<>
<p>Values</p>
{displayValues}
</>
);
}
export default ActivityList;
App.js:
function App() {
return (
<Store>
<div className="App">
<NavBar />
<AllRoutes />
</div>
</Store>
);
}
export default App;
Here's a barebones single-file version of your code that certainly works.
Since you aren't showing how you're mounting your <Map /> and <ActivityList /> components originally, there's not much more I can do to help you with that code, though I will note that it's useless to try and log activities in the same function that has just setActivities, since setState is async (and the function will have captured the earlier activities value anyway).
import React, { useContext, useState, useEffect } from "react";
const delay = (ms) => new Promise((res) => setTimeout(res, ms));
async function getActivityData() {
console.log("calling");
await delay(1000);
return [{ name: "foo", distance: 123 }];
}
function Map() {
const [, setActivities] = useContext(GlobalContext);
useEffect(() => {
getActivityData().then(setActivities);
}, [setActivities]);
return <>map</>;
}
const initState = [];
const GlobalContext = React.createContext();
const Store = ({ children }) => {
const [activities, setActivities] = useState(initState);
return (
<GlobalContext.Provider value={[activities, setActivities]}>
{children}
</GlobalContext.Provider>
);
};
function ActivityList() {
const [activities] = useContext(GlobalContext);
return <div>{JSON.stringify(activities)}</div>;
}
export default function App() {
return (
<Store>
<Map />
<ActivityList />
</Store>
);
}
I am having a very tough time solving this issue
So I have set a context for cart from commerce.js and want to render it on a new page.
I am able to add to cart and all.
The cart object is getting picked in one page, but it to appear in a whole new page so therefore using contexts.
import {createContext, useEffect, useContext, useReducer} from 'react'
import {commerce} from '../../lib/commerce'
//need to correct this file to be a tsx file
const CartStateContext = createContext()
const CartDispatchContext = createContext()
const SET_CART = "SET_CART"
const initialState = {
total_items: 0,
total_unique_items: 0,
line_items: []
}
const reducer = (state,action) => {
switch(action.type){
case SET_CART:
return { ...state, ...action.payload }
default:
throw new Error(`Unknown action: ${action.type}` )
}
}
export const CartProvider = ({children}) => {
const [state, dispatch] = useReducer(reducer, initialState)
const setCart = (payload) => dispatch({type: SET_CART, payload})
useEffect(() => {
getCart()
},[])
const getCart = async() => {
try {
const cart = await commerce.cart.retrieve()
setCart(cart)
} catch (error){
console.log("error")
}
}
return (
<CartDispatchContext.Provider value = {{setCart}}>
<CartStateContext.Provider value = {state}>
{children}
</CartStateContext.Provider>
</CartDispatchContext.Provider>
)
}
export const useCartState = () => useContext (CartStateContext)
export const useCartDispatch = () => useContext (CartDispatchContext)
my _app.tsx
const MyApp = ({ Component, pageProps }: AppProps) => (
<div>
<Web3ContextProvider>
<>
<Component {...pageProps} />
<ToastContainer
hideProgressBar
position="bottom-right"
autoClose={2000}
/>
</>
</Web3ContextProvider>
<CartProvider>
<>
<Component {...pageProps} />
</>
</CartProvider>
</div>
);
export default MyApp;
When I try to render it on the cartPage
import React from "react"
import {CartItem, CartContainer, NavigationBar } from "../components"
import {useRouter} from 'next/router'
import { useCartState, useCartDispatch } from "../context/Cart"
export const CartPage = () => {
const {setCart} = useCartDispatch()
// console.log(setCart)
const {line_items} = useCartState()
// console.log(line_items)
return(
<pre>
{JSON.stringify(line_items,null,2)}
</pre>
)
}
export default CartPage
I get the above Type error
I am not able to figure out what is going wrong. Also if you folks have any other suggestion in next how do i render the cart object in another page
I'm trying to build a simple blog native app using context and have stumbled upon an issue to which I can't find a root to.
Here's the structure of it:
/context/createDataContext.js file:
import React, { useReducer } from "react";
export default (reducer, actions, initialState) => {
const Context = React.createContext();
const Provider = ({ childern }) => {
const [state, dispatch] = useReducer(reducer, initialState);
const boundActions = {};
for (let key in boundActions) {
boundActions[key] = actions[key](dispatch);
}
return (
<Context.Provider value={{ state, ...boundActions }}>
{childern}
</Context.Provider>
);
};
return { Context, Provider };
};
/context/BlogContext.js:
import createDataContext from "./createDataContext";
const blogReducer = (state, action) => {
switch (action.type) {
case "add_blogpost":
return [...state, { title: `Blog Post Number ${state.length + 1}` }];
default:
return state;
}
};
const addBlogPost = (dispatch) => {
return () => {
dispatch({ type: "add_blogpost" });
};
};
export const { Context, Provider } = createDataContext(
blogReducer,
{ addBlogPost },
[]
);
/screens/IndexScreen.js :
import React, { useContext } from "react";
import { View, Text, StyleSheet, FlatList, Button } from "react-native";
import { Context } from "../context/BolgContext";
const IndexScreen = () => {
const { state, addBlogPost } = useContext(Context);
return (
<View>
<Button title="Add a blod post" onPress={addBlogPost} />
<FlatList
data={state}
keyExtractor={(blogPost) => blogPost.title}
renderItem={({ item }) => {
return <Text>{item.title}</Text>;
}}
/>
</View>
);
};
const styles = StyleSheet.create({});
export default IndexScreen;
And finally App.js :
import { NavigationContainer } from "#react-navigation/native";
import { createStackNavigator } from "#react-navigation/stack";
import IndexScreen from "./src/screens/IndexScreen";
import { Provider } from "./src/context/BolgContext";
import React from "react";
const Stack = createStackNavigator();
export default function App() {
return (
<NavigationContainer>
{
<Provider>
<Stack.Navigator initialRouteName="Home">
<Stack.Screen
name="Home"
component={IndexScreen}
options={{ title: "My app" }}
/>
</Stack.Navigator>
</Provider>
}
</NavigationContainer>
);
}
Now I did some debugging, even though the code does't come back with any error, but the issue seems to be on my Provider, since if I remove it I can see content on the screen. Does anybody know why this happens.
Thanks a lot!
You need to change the Provider method like below
Form
const Provider = ({ childern }) => {
To
const Provider = (props) => {
Then you can destructure while passing to the content.provider like below
<Context.Provider value={{ state, ...boundActions }}>
{props.childern}
</Context.Provider>
Hi im new to redux and im trying to create a movie app using the API from www.themoviedb.org. I am trying to display the popular movies and im sure the API link works since ive tested it in postman but i cant seem to figure out why redux doesnt pick up the data.
//action
import { FETCH_POPULAR } from "./types";
import axios from "axios";
export const fetchPopularMovies = () => (dispatch) => {
axios
.get(
`https://api.themoviedb.org/3/movie/popular?api_key=${API}&language=en-US`
)
.then((response) =>
dispatch({
type: FETCH_POPULAR,
payload: response.data
})
)
.catch((err) => console.log(err));
};
//reducer
import { FETCH_POPULAR } from "../actions/types";
const initialState = {
popular: [],
};
export default function (state = initialState, action) {
switch (action.type) {
case FETCH_POPULAR:
return {
...state,
popular: action.payload,
};
default:
return state;
}
}
import React from "react";
import { connect } from "react-redux";
import Popular from "./Popular";
const FetchedPopular = (props) => {
const { popular } = props;
let content = "";
content =
popular.length > 0
? popular.map((item, index) => (
<Popular key={index} popular={item} />
))
: null;
return <div className="fetched-movies">{content}</div>;
};
const mapStateToProps = (state) => ({
popular: state.popular.popular,
});
export default connect(mapStateToProps)(FetchedPopular);
import React from "react";
import "../Styles.css";
const Popular = (props) => {
return (
<div className="movie-container">
<img
className="poster"
src={`https://image.tmdb.org/t/p/w400/${props.poster_path}`}
/>
</div>
);
};
export default Popular;
I cant really tell what I'm missing can someone help?
Next to mapStateToProps you need to create mapDispatchToProps. After that, you will be able to call your Redux action from your React component.
I suggest you the mapDispatchToProps as an Object form. Then you need to use this mapDispatchToProps as the second parameter of your connect method.
When you will have your action mapped to your component, you need to call it somewhere. It is recommended to do it for example on a component mount. As your React components are Functional components, you need to do it in React useEffect hook.
import React, { useEffect } from "react";
import { connect } from "react-redux";
import Popular from "./Popular";
import { fetchPopularMovies } from 'path_to_your_actions_file'
const FetchedPopular = (props) => {
const { popular } = props;
let content = "";
useEffect(()=> {
// call your mapped action (here it is called once on component mount due the empty dependency array of useEffect hook)
props.fetchPopularMovies();
}, [])
content =
popular.length > 0
? popular.map((item, index) => (
<Popular key={index} popular={item} />
))
: null;
return <div className="fetched-movies">{content}</div>;
};
const mapStateToProps = (state) => ({
popular: state.popular.popular,
});
// create mapDispatchToProps
const mapDispatchToProps = {
fetchPopularMovies
}
// use mapDispatchToProps as the second parameter of your `connect` method.
export default connect(mapStateToProps, mapDispatchToProps)(FetchedPopular);
Moreover, as I wrote above in my comment, your Popular does not have the prop poster_path but it has the prop popular which probably has the property poster_path.
import React from "react";
import "../Styles.css";
const Popular = (props) => {
return (
<div className="movie-container">
<img
className="poster"
src={`https://image.tmdb.org/t/p/w400/${props.popular.poster_path}`}
/>
</div>
);
};
export default Popular;
I have been using Redux for a long time, but now decided to try out the new ContextAPI.
I got it working with one component/page (using NextJs), however the state isn't shared between pages/components.
store.js
import React, { createContext, useReducer } from 'react';
import reducer from './reducer'
const initialState = {
players: [],
};
const Store = ({ children }) => {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<Context.Provider value={[state, dispatch]}>
{children}
</Context.Provider>
)
};
export const Context = createContext(initialState);
export default Store;
reducer.js
const Reducer = (state, action) => {
switch (action.type) {
case 'ADD_PLAYER':
return {
...state,
players: [...state.players, action.payload],
};
case 'REMOVE_PLAYER_BY_INDEX':
const array = state.players;
if (array) {
array.splice(action.payload, 1);
}
return {
...state,
players: !array ? [] : array,
};
default:
return state;
}
};
export default Reducer;
add players page /players/add (addplayerspage.js)
import React, { useContext } from 'react';
import map from 'lodash/map';
import isEqual from 'lodash/isEqual';
import { Context } from '../../../context';
const PlayerCreatePage = () => {
const [_, dispatch] = useContext(Context);
const handleAddPlayer = () => {
dispatch({ type: 'ADD_PLAYER', payload: Math.random() });
};
const handleRemovePlayerByIndex = (index) => {
dispatch({ type: 'REMOVE_PLAYER_BY_INDEX', payload: index });
};
return (
<div className="layout">
<div>
<Context.Consumer>
{([state]) => {
const { players } = state;
return map(players, (p, i) => <div
key={i}
onClick={() => handleRemovePlayerByIndex(i)}
>
{p}
</div>
)
}}
</Context.Consumer>
</div>
<button onClick={() => handleAddPlayer()}>Add new</button>
</div>
);
};
export default React.memo(PlayerCreatePage, (prev, next) => isEqual(prev, next));
lobby players page /players/lobby (lobbyplayerspage.js)
import React, { useContext } from 'react';
import map from 'lodash/map';
import { Context } from '../../../context';
const PlayersLobbyPage = () => {
const [state, _] = useContext(Context);
return (
<div>
<div>
{map(state.players, (p, i) => <div
key={i}
>
{p}
</div>
)}
</div>
</div>
);
};
export default PlayersLobbyPage;
_app.js (NextJs)
import App, { Container } from 'next/app';
import '../styles/main.css';
import Store from '../context';
class MyApp extends App {
render() {
const { Component, pageProps } = this.props;
return (
<Container>
<Store>
<Component {...pageProps} />
</Store>
</Container>
);
}
}
export default MyApp;
THE PROBLEM:
Have two tabs open
Add players
Lobby
Add a new player
See that player is added on 'Add players' page
2.See that NOTHING happens on 'Lobby' page
Okay, so the issue is that I was trying to "share" context api state between different open tabs, it doesn't work like that by default, even for redux (tried adding it and faced same result), for redux there's a redux-state-sync library for that, nonetheless I will use sockets in future, so this won't be an issue.
Closed.