marklelapin / thewhaddonshowreact Goto Github PK
View Code? Open in Web Editor NEWThe Whaddon Show App
The Whaddon Show App
https://muhimasri.com/blogs/how-to-create-dynamic-states-with-react-redux/
UPDATE_LIST
generate list of id objects.
UPDATE_ITEM
Change All fields plus isSynced = false
e.g.
const initialState = {};
export const todoReducer = (state = initialState, action) => {
switch (action.type) {
case "UPDATE_TODO_LIST": {
return action.value.reduce(
(accumulator, current) => ({ ...accumulator, [current.id]: current }),
{}
);
}
case "UPDATE_TODO_FIELD": {
return {
...state,
[action.id]: {
...state[action.id],
[action.field]: action.value,
},
};
}
default:
return state;
}
};
Set up Script Component
Redux
Classic/Chat Option
scriptitems of type act, scene (id,parent id)
currentScene
findCurrentScene()
has list of scriptItems in order and assigns scene no.
maps rows of scenes.
switches between different script item types and feeds them scriptitems
remove default of sidebar open
expand rows where long results are shown (default to collapsed)
Confirm Dates button and check boxes need to be aligned vertically in row.
change cross and tick to match the success and failure filters.
Check responsiveness.
Set this up for Persons in Person List component download everything
Go with full download of data and then sync requests are easier it it takes to long for the script then re-think.
the fetch will run a localserverengine sync operation
pass in
stuff marked as unsynced in state to persons/sync
new Ilocalserver
(for a full reset make localcopyid null)
)etc
if localcopy id is null
persons {} = null
scriptitems {} = null
etc
generate new Id
fetch ( persons/sync/{localCopyID}/{unsynced from local})
_localserver = transient and follows builder pattern.
_localserver(savecopyID{x}) - saves in copyId in private variable
_localserver(saveunsynced - saves in unsynced in private variable
postbacks go to private variable etc
_localServer.saveupdatestoLocal adds it to private variable
finaloutput = _localserver.response.build()
return OK (finaloutput)
return
get back updates to be dispatched through UPDATE_SERVER_DATA_LIST into state.persons.[id].latest...,history... etc.
ChatGPT description of how to do the fetch bit below:
To perform a fetch request to update data every 5 seconds in a React component, you can use the setInterval function to create a repeating timer. However, to avoid clashes if a fetch request takes more than 5 seconds, you can follow these best practices:
Use setTimeout and async/await for Fetch:
Instead of using setInterval, use setTimeout to schedule the next fetch request after each successful fetch. This way, you can ensure that the next fetch doesn't start until the previous one has completed, regardless of how long it takes.
Implement Error Handling:
Handle errors gracefully by adding error handling logic to your fetch request. If an error occurs during the fetch, you can still schedule the next fetch but with a delay (e.g., retry after 5 seconds).
Here's an example of how you can set up periodic fetch requests in a React component:
javascript
Copy code
import React, { useEffect } from 'react';
function YourComponent() {
const fetchData = async () => {
try {
const response = await fetch('your-api-endpoint');
if (!response.ok) {
throw new Error('Network response was not ok');
}
const data = await response.json();
// Update your state or Redux store with the fetched data here
// Schedule the next fetch after 5 seconds
setTimeout(fetchData, 5000);
} catch (error) {
console.error('Error fetching data:', error);
// If an error occurred, retry the fetch after 5 seconds
setTimeout(fetchData, 5000);
}
};
useEffect(() => {
// Start the initial fetch when the component mounts
fetchData();
// Don't forget to clean up the timer when the component unmounts
return () => {
clearTimeout();
};
}, []);
return (
// Your component JSX here
);
}
export default YourComponent;
In this example, we use setTimeout for scheduling the next fetch request after either a successful fetch or an error. This approach ensures that fetch requests won't overlap, and if one fetch takes longer than 5 seconds, the next one will still be scheduled correctly.
Additionally, remember to clean up the timer using clearTimeout when the component unmounts to prevent any potential memory leaks.
User
how would this look in a class component
ChatGPT
To achieve periodic fetch requests in a class component, you can use the componentDidMount lifecycle method to start the initial fetch and componentWillUnmount to clean up the timer. Here's how you can implement it in a class component:
javascript
Copy code
import React, { Component } from 'react';
class YourComponent extends Component {
constructor(props) {
super(props);
this.fetchTimer = null; // Initialize a timer reference
}
componentDidMount() {
this.fetchData(); // Start the initial fetch when the component mounts
}
componentWillUnmount() {
// Clean up the timer when the component unmounts
clearTimeout(this.fetchTimer);
}
fetchData = async () => {
try {
const response = await fetch('your-api-endpoint');
if (!response.ok) {
throw new Error('Network response was not ok');
}
const data = await response.json();
// Update your state or Redux store with the fetched data here
// Schedule the next fetch after 5 seconds
this.fetchTimer = setTimeout(this.fetchData, 5000);
} catch (error) {
console.error('Error fetching data:', error);
// If an error occurred, retry the fetch after 5 seconds
this.fetchTimer = setTimeout(this.fetchData, 5000);
}
};
render() {
return (
// Your component JSX here
);
}
}
export default YourComponent;
This code follows the same logic as the functional component example but adapted for a class component. The componentDidMount method initiates the initial fetch, and the componentWillUnmount method cleans up the timer to prevent memory leaks.
Make sure to replace 'your-api-endpoint' with your actual API endpoint and handle the fetched data according to your application's needs.
Scene Header
Redux
gets Scene and synopsis and initial staging (if follows on from synopsis or scene) SCriptItems from redux store
get script items id,created,type,parentId for all history from redux store given id prop passed in
Classic/Chat ?? if can't be done through css
State
Histroy = get from selector id,created,type,parentId (sorted by PArentId)
UndoDate = null
returns
Scene Header script Item
add and edit parts in Parts Section
show video or audio attached to scene.
edit synopsis
Add props
Initial Staging
Undo buttons => hanlgeCreatedDateChange = updates History
on select use these = dispatch(update REducx)
map => Script Item components passing in id. createdDate
With Pagination and Filters
using text box checkbox components already setup etc.
need some mechanism to deal with prevState and current state with ccomponent to highlight changes.
this.state = firstName
LastName
etc
change handlers update component state.
and showConfirmButtons = true
showConfirmButtons - confirm and cancel icon. click cancel
on cancel -restore state to original state.
on confirm - dispatch to UPDATE_ITEM
need to understand how useSelector works in component below.
const TextBox = ({id}) => {
const value = useSelector(state => state[id]?.title)
return
}
const CheckBox = ({id}) => {
const value = useSelector(state => state[id]?.completed);
return
}
change handlers update component state.
and showConfirmButtons = true
showConfirmButtons - confirm and cancel icon. click cancel
TickCross functions need danger and success colors to be added
at some point ( i think on resizing the open and close gets out of sycn with each other)
<Joyride
callback={this.handleJoyrideCallback}
continuous={true}
run={this.state.run}
showSkipButton={true}
steps={this.state.steps}
spotlightPadding={-10}
disableOverlay={true}
disableScrolling
styles={{
options: {
arrowColor: '#ffffff',
backgroundColor: '#ffffff',
overlayColor: 'rgba(79, 26, 0, 0.4)',
primaryColor: '#000',
textColor: '#495057',
spotlightPadding: 0,
zIndex: 1000,
padding: 5,
width: 240,
},
tooltip: {
fontSize: 15,
padding: 15,
},
tooltipContent: {
padding: '20px 5px 0',
},
floater: {
arrow: {
padding: 10
},
},
buttonClose: {
display: 'none'
},
buttonNext: {
backgroundColor: "#21AE8C",
fontSize: 13,
borderRadius: 4,
color: "#ffffff",
fontWeight: "bold",
outline: "none"
},
buttonBack: {
color: "#798892",
marginLeft: 'auto',
fontSize: 13,
marginRight: 5,
},
buttonSkip: {
color: "#798892",
fontSize: 13,
},
}}
/>
Surrounds different script itme type with comment and histroy functionalitiy etc
Works like the User component.
recieved id, created date, onCreateNew, onChangeCreatedDate
Redux
for script item id. history
plus if child of script item is of type comment then the comment
NB HAVE TO WORK OUT LOGIC OF KEEPIN COMMENT IF REVERT TO DIFFERENT VERSION
State
SelectedUpdate
add new item below
add comment (new item below)
dipatch(saveUpate())
handle loss of focus => handle update
handle save => dispatches to REdux
handle change of type = changes selectedUpdate type
handle addnewscriptitem => handle save + onCreateNew passed baclk
handlePart Change
choose component to render depending on type and passes into these a script item., PartChange,TextChange,onTagsChange
handleCreateDateChange
=> onChangecreateDate passed
needs to make sync.localCopyId = null
sync
then
persons.RESET_LIST
scriptItems.RESET_LIST etc.
Set this up using QUERY Component -DOESNT HAVE TO WRAP AROUND EVERYTHING AS WILL CHANGE THE State for stuff below.
fetch the data - do this by performing sync operation --- SEE FOLLOWING ISSUE AS WELL AND COMBINE THE TWO,
Only server actions needs to be persons/sync
replace setToDoList(data) with setPersonLIst(data) dispatching PERSON_UPDATE_LIST
useEffect(() => {
async function getTodoList() {
const response = await fetch("https://jsonplaceholder.typicode.com/todos");
const data = await response.json();
dispatch({
type: "UPDATE_TODO_LIST",
value: data,
});
setTodoList(data);
}
getTodoList();
}, []);
have stuff below refer to state.persons. etc
Account Dropdown a bit lower than other dropdowns
Get all updates etc should at least be referring to server (not local)
all data between server and local should just be handled by sync.
if local data is corrupted or being setup for first time. reset localcopyId and sync will return all data.
this should include GetUpdatesFromLocal
Reset Sample Data
Get Local LAst sync Date
see - ReactLocalDataAccess for further notes.
Need to check ILocalDataAccess and original methods also before proceeding.
class for different types
final thing should be structured a bit like this but with significant differences as dicussed in previosu issues.
import { useState, useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import "./todo.css";
export const TodoList = () => {
const [todoList, setTodoList] = useState([]);
const dispatch = useDispatch();
useEffect(() => {
async function getTodoList() {
const response = await fetch(
"https://jsonplaceholder.typicode.com/todos"
);
const data = await response.json();
dispatch({
type: 'UPDATE_TODO_LIST',
value: data
});
setTodoList(data);
}
getTodoList();
}, []);
return (
Task | Completed |
---|---|
To update local storage after a Redux state change in a React application, you can follow these steps:
Install and Set Up Redux: If you haven't already, set up Redux in your React application. You can use the redux
and react-redux
libraries. You can find the official Redux documentation here: https://redux.js.org/introduction/getting-started
Create Redux Actions and Reducers: Define the actions and reducers to manage the state you want to store in local storage.
Update State with Redux: Use Redux to update the state. When you dispatch actions that modify the state, Redux will handle the updates for you.
Create a Local Storage Helper Function: Create a helper function that interacts with local storage to save and retrieve data.
Here's an example of how you can create a helper function for local storage:
// localStorage.js
// Save data to local storage
export const saveState = (state) => {
try {
const serializedState = JSON.stringify(state);
localStorage.setItem('myAppData', serializedState);
} catch (error) {
// Handle errors, e.g., quota exceeded
console.error('Error saving state to local storage:', error);
}
};
// Load data from local storage
export const loadState = () => {
try {
const serializedState = localStorage.getItem('myAppData');
if (serializedState === null) {
return undefined; // If no data is stored, return undefined to use the initial state
}
return JSON.parse(serializedState);
} catch (error) {
// Handle errors, e.g., invalid JSON
console.error('Error loading state from local storage:', error);
return undefined; // Return undefined on error to use the initial state
}
};
store.subscribe()
method to listen for changes in your Redux store. When the state changes, call the saveState
function to update local storage.Here's an example of how you can set up the subscription in your React application:
import { saveState, loadState } from './localStorage';
import { createStore } from 'redux';
import rootReducer from './reducers'; // Import your Redux root reducer
// Create the Redux store with the initial state loaded from local storage
const initialState = loadState();
const store = createStore(rootReducer, initialState);
// Subscribe to Redux store changes and update local storage
store.subscribe(() => {
saveState(store.getState());
});
Now, whenever the Redux state changes, it will be automatically saved to local storage. When your application starts, it will load the initial state from local storage.
Remember to handle any potential errors that may occur during local storage interactions, such as exceeding the storage quota or parsing errors, as shown in the localStorage.js
example.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.