Git Product home page Git Product logo

thewhaddonshowreact's People

Contributors

marklelapin avatar

Watchers

 avatar

thewhaddonshowreact's Issues

Setup PersonReducer

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;
}
};

Script Component

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.

Api Test Results Page Tidy Up

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 up update regular fetch request to sync state with server.

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

run sync operation in .net using local server engine.

new Ilocalserver

  1. get localcopyid from state

(for a full reset make localcopyid null)

)etc

if localcopy id is null
persons {} = null
scriptitems {} = null
etc
generate new Id

  1. get unsynced from state ( those with out updated on server date)

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 Component

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

Create Person Table Row Component

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

Add JoyRide back into header? -this is the take a tour thing.

<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,
},
}}
/>

ScriptItem Component

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

setup <QUERY> component in persons table list

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

Remove deprecated functionality from LocalServerModel methods

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.

Add in table list to page component using map.

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 (









{todoList.map((item) => (




))}

Task Completed

);
};
const TextBox = ({id}) => {
const value = useSelector(state => state[id]?.title)
const dispatch = useDispatch();
function changeHandler(e) {
dispatch({
type: 'UPDATE_TODO_FIELD',
id, value: e.target.value, field: 'title'
})
}
return
}
const CheckBox = ({id}) => {
const value = useSelector(state => state[id]?.completed);
const dispatch = useDispatch();
function changeHandler(e) {
dispatch({
type: 'UPDATE_TODO_FIELD',
id, value: e.target.checked, field: 'completed'
})
}
return
}

Add in helper to link state to LocalStorage

To update local storage after a Redux state change in a React application, you can follow these steps:

  1. 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

  2. Create Redux Actions and Reducers: Define the actions and reducers to manage the state you want to store in local storage.

  3. 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.

  4. 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
  }
};
  1. Subscribe to Redux State Changes: You can use the 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.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.