Reputation: 171
I have a task to
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;
Upvotes: 0
Views: 1294
Reputation: 171
So,i managed how to do this task,it wasnt easy but i got to the end. I used react hooks and local storage to store the states of the buttons to mentain the values on page refresh and the problem with buttons i solved with hooks too. The whole component is below:
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 (isSubscribed = 'Unsubscribe') {
// setDisplay = 'none'
// //localStorage.setItem('isSubscribed', 'true')
// } else if (isSubscribed ='Subscribe') {
// 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
let [isDisabled, setDisabled] = useState(false)
let [isSubscribed, setSubscribe] = useState('Subscribe')
let [status, setStatus] = useState(false);
let [displayMode, setDisplay] = useState('block')
const [opacity, setOpacity] = useState(1);
useEffect(() => {
const buttonState = localStorage.getItem('Button state')
if (buttonState) {
setSubscribe(JSON.parse(buttonState))
}
}, [])
useEffect(() => {
const statusState = localStorage.getItem('isSubmited')
if (statusState) {
setStatus(JSON.parse(statusState))
}
}, [])
useEffect(() => {
const displayMode = localStorage.getItem('displayMode')
if (displayMode) {
setDisplay(JSON.parse(displayMode))
}
}, [])
useEffect(() => {
localStorage.setItem('Button state', JSON.stringify(isSubscribed))
localStorage.setItem('isSubmited', JSON.stringify(status))
localStorage.setItem('displayMode', JSON.stringify(displayMode))
})
// if (isSubscribed === 'Unsubscribe') {
// setDisplay('none')
// //localStorage.setItem('isSubscribed', 'true')
// } else if (isSubscribed === 'Subscribe') {
// setDisplay('block')
// //localStorage.setItem('isSubscribed', 'false')
// }
// 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 (isDisabled) return // do nothing if request already made
//setDisabled(true)
disableBtn()
const response = await fetchMock() //eslint-disable-line
// isFetching = false
//setDisabled(false)
enableBtn()
setStatus(true)
if (validateEmail(introducedEmail) == false) {
setStatus(false)
}
}
const fetchMock = () => {
return new Promise(resolve => setTimeout(() => resolve('hello'), 2000))
}
const disableBtn = () => {
// button.disabled = true
// button.style.opacity = '0.5'
setOpacity(0.5)
setDisabled(true);
}
const enableBtn = () => {
// button.disabled= false
// button.style.opacity = '1'
setOpacity(1)
setDisabled(false);
}
//let opacityValue =1
//props.disabled ? 0.5 : 1;
const undoClickButton = () => {
unsubscribeEmail()
setStatus(false)
}
const changeButtonState = () => {
status ? undoClickButton() : submitClickButton()
}
const subscribe = () => {
// const subscribeBtn = document.getElementById('subscribeButton')
setSubscribe('Unsubscribe')
// document.getElementById('emailForm').style.display = 'none'
localStorage.setItem('isSubscribed', 'true')
setDisplay('none')
console.log(status)
// setEmail('')
//document.getElementById('submit-info').value = ''
//localStorage.setItem('Email', '')
}
const unsubscribe = () => {
//const subscribeBtn = document.getElementById('subscribeButton')
setSubscribe('Subscribe')
//document.getElementById('emailForm').style.display = 'block'
localStorage.setItem('isSubscribed', 'false')
setDisplay('block')
console.log(status)
}
const subscribeEmail = (email) => {
const isValidEmail = validateEmail(email)
if (isValidEmail === true) {
subscribe()
} else if (isValidEmail === false) {
unsubscribe()
}
}
const unsubscribeEmail = () => {
unsubscribe()
unsubscribeUser()
setEmail('')
localStorage.removeItem('Email')
}
//--------------------------------------
return (
<>
<main id='app-container'>
<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
className="form-wrapper"
id="emailForm"
style={{
display: displayMode
}}
>
<input
className='form-input'
id='submit-info'
type='text'
placeholder='Email'
value={email}
onChange={(e) => setEmail(e.target.value)}
></input>
</div>
<input
id='subscribeButton'
className='app-section__button submit-btn'
type='button'
value={isSubscribed}
style={{
opacity
}}
onClick={() => { changeButtonState() }}
disabled={isDisabled} ></input>
</form>
</section>
</main>
</>
)
}
export default JoinUsSection
Upvotes: 1