I have a task to
- Implement the functionality of sending a user’s email to the server when they click on the “Subscribe” button. To do this, make a POST Ajax request using the /subscribe endpoint.
- Implement the functionality of unsubscribing the user’s email from
the community list when they click on the “Unsubscribe” button. To do
this, make a POST Ajax request using the /unsubscribe endpoint. - Prevent additional requests if the “Subscribe” and “Unsubscribe”
buttons are pressed while requests to the /subscribe and /unsubscribe
endpoints are in progress. Also, disable them (using the disabled
attribute) and style them using opacity: 0.5. using React.Redux library is prohibited.
So,i have did this task,but the problem is that my form is not doing unsubscribe state,it leaves the email unchanged and the button doesnt change its state from unsubscribe to subscribe,but as a result,when an email is valid,it should give the possibility of sending subscribe fetch request to the server and the button text to change in Unsubscribe and the display of the form to be none,but if the email is not valid,then the button should have the Subscribe text,no fetch request possibilities and the input form to have the display block.Besides this,the value to be stored in local storage and when the page refreshes it leaves the form in the state it was,if was subscribed then all the changes for subscribe are actual and if not than vice-versa.
I have did this task using only javascript and it works as follows:
non-valid email:
So,the question is,what i am doing wrong? Why only subscribe fetch works and how to fix the form to make the requested result,i’m exhausted,three days i try to answer this question and i dont understand anything.. please help,thanks in advance!
JoinUsSection component with the form :
import { useState, useEffect } from "react"
import { sendSubscribe } from "../scripts/subscribeFetch"
import { validateEmail } from "../scripts/email-validator"
import { unsubscribeUser } from "../scripts/unsubscribeFetch"
const JoinUsSection = props => {
const { placeholder } = props
//Input div functions
let isSubscribedd = localStorage.getItem('Email') //Function for setting display to none if the form is subscribed and display to block
//console.log(validateEmail(isSubscribedd)) //if form is unsubscribed
let validatedEmail = validateEmail(isSubscribedd)
let setDisplay = ''
if (validatedEmail === true) {
setDisplay = 'none'
localStorage.setItem('isSubscribed', 'true')
} else if (validatedEmail === false) {
setDisplay = 'block'
localStorage.setItem('isSubscribed', 'false')
}
//-------------------------------------
//Input type text Functions
const [email, setEmail] = useState(() => {
//reading data from localStorage
const localEmail = localStorage.getItem('Email')
const initialValue = localEmail
if (localStorage.getItem('Email') !== null) {
return initialValue
} else {
return placeholder
}
})
useEffect(() => {
//storing input email in localStorage
const introducedEmail = email
//console.log(introducedEmail)
localStorage.setItem('Email', introducedEmail)
}, [email])
//------------------------------------------------------
//Input type button Functions
const [isDisabled, setDisabled] = useState(false)
const [isSubscribed, setSubscribe] = useState('Subscribe')
let isFetching = false
let isUsed = false
let introducedEmail = email
const submitClickButton = async () => {
subscribeEmail(introducedEmail) //change the button style and set in local storage isSubscribed to true
sendSubscribe(introducedEmail) //send subscribe fetch to the server
// prevent additional requests upon clicking on "Subscribe" and "Unsubscribe".
if (isFetching) return // do nothing if request already made
isFetching = true
disableBtn()
const response = await fetchMock() //eslint-disable-line
isFetching = false
enableBtn()
isUsed = true
if (validateEmail(introducedEmail) == false) {
isUsed = false
}
}
const fetchMock = () => {
return new Promise(resolve => setTimeout(() => resolve('hello'), 2000))
}
const disableBtn = () => {
// button.disabled = true
// button.style.opacity = '0.5'
setDisabled(true);
}
const enableBtn = () => {
// button.disabled= false
// button.style.opacity = '1'
setDisabled(false);
}
const opacityValue = props.disabled ? 0.5 : 1;
const undoClickButton = () => {
unsubscribeEmail()
isUsed = false
}
const changeButtonState = () => {
isUsed ? undoClickButton() : submitClickButton()
}
const subscribe = () => {
// const subscribeBtn = document.getElementById('subscribeButton')
setSubscribe('Unsubscribe')
// document.getElementById('emailForm').style.display = 'none'
localStorage.setItem('isSubscribed', 'true')
console.log(isUsed)
//document.getElementById('submit-info').value = ''
introducedEmail = ''
}
const unsubscribe = () => {
//const subscribeBtn = document.getElementById('subscribeButton')
setSubscribe('Subscribe')
//document.getElementById('emailForm').style.display = 'block'
localStorage.setItem('isSubscribed', 'false')
console.log(isUsed)
}
const subscribeEmail = (email) => {
const isValidEmail = validateEmail(email)
if (isValidEmail === true) {
subscribe()
} else if (isValidEmail === false) {
unsubscribe()
}
}
const unsubscribeEmail = () => {
unsubscribe()
unsubscribeUser()
localStorage.removeItem('Email')
}
//--------------------------------------
return (
<>
<section className='app-section app-section--image-program' id='programContainer'>
<h2 className='program-title'>Join Our Program</h2>
<h3 className='program-subtitle'>Sed do eiusmod tempor incididunt<br />ut labore et dolore magna aliqua</h3>
<form className='submitFieldWrapper' id='form'>
<div
style={{
display: setDisplay
}}>
<input
className='form-input'
id='submit-info'
type='text'
placeholder='Email'
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
</div>
<input
id='subscribeButton'
className='app-section__button submit-btn'
type='button'
value={isSubscribed}
style={{
opacity: opacityValue
}}
onClick={() => changeButtonState()}
disabled={isDisabled} />
</form>
</section>
</>
)
}
export default JoinUsSection
subscribe fetch request,in different folder and file:
import { validateEmail } from './email-validator.js'
export const sendSubscribe = (emailInput) => {
const isValidEmail = validateEmail(emailInput)
if (isValidEmail === true) {
sendData(emailInput)
}
}
export const sendHttpRequest = (method, url, data) => {
return fetch(url, {
method: method,
body: JSON.stringify(data),
headers: data
? {
'Content-Type': 'application/json'
}
: {}
}).then(response => {
if (response.status >= 400) {
return response.json().then(errResData => {
const error = new Error('Something went wrong!')
error.data = errResData
throw error
})
}
return response.json()
})
}
const sendData = (emailInput) => {
sendHttpRequest('POST', '/subscribe', {
email: emailInput
}).then(responseData => {
return responseData
}).catch(err => {
console.log(err, err.data)
window.alert(err.data.error)
})
}
email validator ,in different folder and file:
const VALID_EMAIL_ENDINGS = ['gmail.com', 'outlook.com', 'yandex.ru']
export const validateEmail = (email) => !!VALID_EMAIL_ENDINGS.some(v => email.includes(v))
export { VALID_EMAIL_ENDINGS as validEnding }
unsubscribe fetch request,in different folder and file:
export const unsubscribeUser = () => {
fetch('/unsubscribe', { method: 'POST' }).then(response => { console.log(response.status) })
}
App.js:
import './App.css';
import JoinUsSection from './components/JoinUsSection';
function App() {
return (
<JoinUsSection/>
);
}
export default App;