React: GlobalState updates

Remove DataCtx dependacy on AppCtx
This commit is contained in:
djmil 2023-10-19 14:39:43 +02:00
parent efd7127575
commit 5821a02ba1
5 changed files with 24 additions and 14 deletions

View File

@ -3,13 +3,13 @@ import { AppData } from "../../context/data"
import { AppContext } from "../../context/app"
export default function DataPolling() {
const [appData] = React.useContext(AppData)
const [appCtx, dispatchAppData] = React.useContext(AppContext)
const [appData, dispatchData] = React.useContext(AppData)
//const [appCtx, dispatchAppData] = React.useContext(AppContext)
return <div className={DataPolling.name}>
polling
<button onClick={() => dispatchAppData({type: "togglePolling"})}>
{ appCtx.disablePolling === true ? "off" : "on" }
<button onClick={() => dispatchData({type: "togglePolling"})}>
{ appData.disablePolling === true ? "off" : "on" }
</button>
{ appData.fetching }
</div>

View File

@ -1,16 +1,12 @@
export const reducer = (state, action) => {
switch (action.type) {
case "togglePolling":
return { ...state,
disablePolling: !state.disablePolling // on/off
}
default:
console.warn("Unknown action.type", action)
return state
}
}
export const initialState = {
disablePolling: false,
myState: false,
}

View File

@ -1,5 +1,14 @@
import { useState, useCallback, useEffect, } from "react"
/*
TODO: Poll(uri, flavour)
- uri: string
- execution_flvour:
- once (i.e. now)
- interval (sec)
- stop
*/
export default function Poll(url, interval_sec, disabled) {
const [cache, setCache] = useState(null)
const [fetching, setFetching] = useState(false)

View File

@ -1,6 +1,5 @@
import React from "react"
import { reducer, initialState } from "./reducer"
import { AppContext } from "../app"
import Poll from "./Poll"
@ -12,10 +11,9 @@ export const AppData = React.createContext({
export const AppDataProvider = ({ children }) => {
const [data, dispatchData] = React.useReducer(reducer, initialState)
const [appContext] = React.useContext(AppContext)
const games = Poll('api/gamestate', 30, appContext.disablePolling)
const leaderboard = Poll('api/leaderboard', 60, appContext.disablePolling)
const games = Poll('api/gamestate', 30, data.disablePolling)
const leaderboard = Poll('api/leaderboard', 60, data.disablePolling)
data.games = games.data
data.leaderboard = leaderboard.data

View File

@ -1,6 +1,11 @@
export const reducer = (state, action) => {
switch (action.type) {
case "togglePolling":
return { ...state,
disablePolling: !state.disablePolling // on/off
}
default:
console.warn("Unknown action.type", action)
return state
@ -10,5 +15,7 @@ export const reducer = (state, action) => {
export const initialState = {
games: null,
leaderboard: null,
disablePolling: false,
fetching: []
}