Act as a React web developer expert.
This is my AddRoute.jsx:
import { useEffect, useState } from 'react';
import { Alert, Col, Container, Row } from 'react-bootstrap';
import { ActionList, BlockList, CreatePageBody, Title } from './AddComponents';
import { BackButton } from './NavigationComponents';
import API from '../API';
This is my AddComponents.jsx:
import 'bootstrap-icons/font/bootstrap-icons.css';
import '../style.css';
import { Accordion, Button, ButtonGroup, Card, Col, Form, ListGroup } from 'react-bootstrap';
import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import API from '../API';
import dayjs from 'dayjs';
//Can't get it from database because it is not saved.
//This number is used only for triggering the re-render of the content of the Forms of each block showed at video. (ex when handleUp or handleDown)
function generatelocalId() {
return Math.random().toString(36).substring(2) + Date.now().toString(36);
}
// Placed here because otherwise handleAction couldn't call navigate.
// Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component.
const navigate = useNavigate();
const [date, setDate] = useState(""); // Used to publish programmed pages
const list = props.list;
const title = props.title;
return (
<Col className="pt-4">
<Button variant="warning" style={{ marginBottom: "2%", width: "100%" }} onClick={() => handleAction("draft")}>Save as Draft</Button>
<Button variant="success" style={{ marginBottom: "10%", width: "100%" }} onClick={() => handleAction("publish")}>Publish</Button>
<Form.Control type="date" name="date" value={date} onChange={(ev) => setDate(ev.target.value)} />
<Button variant="secondary" style={{ marginTop: "2%", width: "100%" }} onClick={() => handleAction("programmed")}>Schedule Publication</Button>
</Col>
);
function handleAction(action) {
let valid = true;
let data = {};
if (title.trim() == "") {
valid = false;
props.handleError("You have to choose a title for the page.");
}
else if (!(list.some(item => item.blockType == 'Header')) ||
(!(list.some(item => item.blockType == 'Paragraph') || list.some(item => item.blockType == 'Image')))
) {
valid = false;
props.handleError("You have to insert at least a Header and a Paragraph/Image.");
}
else if (list.some(item => (item.content.trim() == ""))) {
valid = false;
props.handleError("At least one block without content!");
}
if (valid) {
data = { // Data formatted. Ready to send it to the server for Page Creation.
title: title,
blocks: JSON.stringify(list) // Saved directly as json in db
};
switch (action) {
case "draft":
Object.assign(data, { publishDate: null });
break;
case "publish":
Object.assign(data, { publishDate: dayjs().format("YYYY-MM-DD") });
break;
case "programmed":
const Date = dayjs(date);
if (!Date.isValid() || Date.isBefore(dayjs())) { //dayjs() returns today date
props.handleError("Select a valid date.");
return;
}
Object.assign(data, { publishDate: Date.format("YYYY-MM-DD") });
break;
default:
break;
}
API.createPage(data)
.then(() => {
navigate("/backoffice")
})
.catch((err) => props.handleError(err));
}
}
In AddComponents.jsx how can I avoid doing x.content = ev.target.value ? And, is it wrong anyway?
Assistant
You can avoid directly modifying x.content by implementing a callback function that updates the state in the parent component (AddRoute.jsx) instead. In a more functional approach, you can use an onContentChange callback to pass the updated value back to the parent component. Here's the updated code:
In AddRoute.jsx, create a new function called updateBlockContent:
Now, the x.content value is not directly modified, instead, the parent component is responsible for updating it, making sure the state is managed properly.
Directly modifying the content with x.content = ev.target.value is not advised because it goes against the principles of React's state management. Ideally, you should always use the setState methods or callback functions to update the state, to ensure that React can track and optimize the updates efficiently.
User
Doing so, I can't write more than one character without re-selecting the form to continue writing.
Assistant
I apologize for the confusion. I've double-checked the code and it seems I missed the fact that the changes are still being passed to the parent component, thus causing a re-render during the editing process. To resolve this issue, you can debounce the updateBlockContent function to limit the number of updates. This way, the local content state in MyBlock will still handle the fast input changes, and the debounced version of updateBlockContent will only be called after a certain period of inactivity.
First, add a useDebouncedEffect custom hook to handle the debounced updates inside the MyBlock component:
Now, the parent component will be updated only after the debounce delay, allowing you to write multiple characters without having to re-select the form. This approach will give a better user experience while still keeping the state in the parent component updated.
User
more easy way?
Assistant
Apologies for any confusion earlier. Here's a simpler and more straightforward method to achieve the same goal without using debouncing. You can update the parent state only when the MyBlock component is blurred (i.e., when the focus is lost).
Modify the MyBlock component in AddComponents.jsx:
Now, the parent component's state will be updated only when the focus is lost from the input elements in the MyBlock component. This approach allows for seamless editing and only updates the parent component when necessary.
User
Nice solution but if I am writing and I press the handle up button nothing happens because only onBlur is called and not the button I pressed
Assistant
You're right, my solution doesn't account for that. Since the onBlur event gets fired before the click event on the handle up or handle down buttons, you would need a different approach.
Instead, you can use a combination of useState and useEffect to save changes at the local level of the MyBlock component without immediately updating the parent's state and then call the parent's update function when the component is unmounted.
First, change the onChange event handler in the MyBlock component to only update the local state:
Now, any input changes will only update the local state, allowing you to type smoothly and interact with the handle up and handle down buttons. The parent's state will be updated only when the MyBlock component is unmounted, ensuring the parent always has the most recent changes.
User
Warning: Maximum update depth exceeded. This can happen when a component calls setState inside useEffect, but useEffect either doesn't have a dependency array, or one of the dependencies changes on every render.
Assistant
Apologies for the confusion. It seems I overlooked the dependencies in the useEffect callback. The best approach in this case would be to keep a reference to the current content value using useRef and update that reference on every change. Later, within the useEffect, you can use the referenced value to call the parent's update function when the component is unmounted. Here's the updated code:
First, import useRef:
javascript
import { useState, useRef, useEffect } from 'react';
In this MyBlock component, we use the block's id as a key and store the local blockData state. The handleContentChange function updates this local state and sends the new block data to the updateBlockContent callback in the AddRoute component.
Now, modify the updateBlockContent function in AddRoute:
This should solve the issue and allow you to properly update the content of the MyBlock component without causing excessive re-renders or blocking interactions with other buttons.
User
Too difficult. I need a very much simple way to handle content reflection.
Assistant
I apologize for the complexity of earlier solutions. A simple approach to reflecting content is to use a two-way data binding method with a local state and update the parent component's state when the focus is lost.
Here's a simplified solution:
In AddComponents.jsx, change the onChange event handlers to only set the local content:
This way, the parent component will be updated only when you lose focus on the input field, and you can work with the handle up and handle down buttons without any conflict. This approach is simpler and keeps the component structure fairly straightforward.
User
it's an amazing solution but if I am writing inside the form and then I press handle up, handle up doesn't work because it triggers onblur condition
Assistant
I understand the issue you're encountering. Let's use an alternative approach - instead of using the onBlur event to update the parent state, we'll update the state only when clicking the handleUp and handleDown buttons. To do this, we need to modify the handleUp and handleDown functions in the MyBlock component.
In AddComponents.jsx, remove the onBlur event handlers for the textarea and radio button input.
Now, when you're writing inside the input field and press the handle up or handle down buttons, the parent state will be updated first, and then the order of the blocks will be changed. This approach should resolve the issue you were encountering earlier.
User
yes but like that when I handleup only the content of x block is reflected and not the other block I am moving
Assistant
I apologize for the oversight. To update the content of both blocks involved in the swapping operation, you can create a custom function that updates both blocks and then trigger it in the handleUp and handleDown functions.
In AddComponents.jsx, create a new function called updateBlocksAndSwap:
Now, when you move a block up or down by clicking the handle up or handle down buttons, the content of both blocks involved in the swapping operation will be updated in the parent state.
This approach should resolve the issue while keeping the logic within the MyBlock component.
User
too difficult. I want the changes to be reflected when I press anything else than the box
Assistant
I apologize for the complexity of the previous solutions. Here's a simpler approach, which updates the parent state when you click outside of the textarea or radio inputs inside the MyBlock component.
In AddComponents.jsx, wrap the content of the MyBlock component in a div with an onBlur event handler:
The handleClickOut function checks if the related target (the element receiving focus) is not a child of the current MyBlock component. If it's not, it updates the parent state.
Now, whenever you click outside of the textarea or radio input, the changes will be reflected in the parent state, and the handle up and handle down buttons will work as intended.
User
so When I click the handle up button it will trigger both onblur and handle up?
Assistant
Yes, you're right. Upon clicking the handle up button, both the onBlur event of the div and the handleUp in the MyBlock component will be triggered. The onBlur event will update the parent state with the current content, while the handleUp function is responsible for changing the order of the blocks.
This ensures that the changes to the content will be reflected in the parent state when clicking outside of the textarea or when using the handleUp button, thus achieving the desired behavior.
User
It does not trigger both two. When I click the handle up button it triggers only the onblur, I have to click a second time to handle up!
Assistant
You are right, and I apologize for the misunderstanding. The click event in the handle up and handle down buttons is being interrupted by the onBlur event, which is causing the problem you're experiencing.
A simple workaround is to add a timeout to the handle up and handle down buttons' click event handlers that provides a small grace period for onBlur to be fired, allowing both events to occur. We'll create a handleButtonClick function that wraps the actual handling with a timeout:
In AddComponents.jsx, modify the MyBlock component:
With this change, when you click the handle up or handle down buttons, it should trigger both onBlur and the button click handlers. It will allow the proper updating of the parent state while also changing the order of the blocks as expected.
User
Too difficult. Rethink the whole process and please provide me changes for a better solution
Assistant
I apologize for the confusion earlier. Here's a more straightforward solution to achieve the desired behavior without using onBlur:
Modify the handleUp and handleDown functions in MyBlock to accept the content as an extra parameter, and pass it to props.updateBlockContent:
You can now remove the onBlur event handler from the div wrapping the content of the MyBlock component.
Now, when you press the handle up or handle down button, the changes will be reflected in the parent state by both updating the block content and changing the block order.
Alternatively, here's a simpler solution:
In the handleUp and handleDown functions, update the blocks in the parent state without using the props.updateBlockContent:
javascript
User
if I change block 1 order to block 2, to only one of the 2 blocks the changes will be reflected
Assistant
You're right, my previous response only updated the content of the block being dragged up or down. To reflect the changes in both the blocks involved in the swapping operation, let's slightly modify the handleUp and handleDown functions to update the content in both blocks.
In AddComponents.jsx, modify the handleUp and handleDown functions of the MyBlock component:
Now, when you change the order of the blocks, the content changes will be reflected for both blocks that are being swapped. This approach will ensure that the parent component's state is updated accurately.
User
How can I update a state without triggering the re-render?
Assistant
You cannot update a state in React without triggering a re-render because React is designed to re-render a component whenever its state updates. This is the core concept of React's reactive nature.
However, if you wish to store a value without triggering a re-render, you can use useRef.
useRef creates a mutable object with a current property. Unlike state updates, when the current property is changed, it does not cause a re-render of the component. It is useful for storing values without provoking a re-render or for instance in retaining DOM elements across renders.
Here's an example showing how to use useRef for storing a value without causing re-render
Remove the onBlur event handler from the div wrapping the content of the MyBlock component.
With this approach, the content state stays local to the MyBlock component, and only the block order is being updated in the parent state. When you press the handle up or handle down button, the changes will be reflected in the parent state, and the block order will be updated correctly.