Hi im making an interactive price calculator for a sales site that allows the user to click on features that increase a numeric value. I have decided to do the entire thing in useState useEffect before i bring in context to the website.
What you are seeing is the useeffect part i dont want to bring in context yet but im setting up to do that later.
const ToolSelect = () => {
useEffect(() => {
setInitialState(initialState);
}, []);
const [initialState, setInitialState] = useState({
service: "",
services: [],
plan: "",
type: "",
clicked: false,
price: 0
});
const { number, service } = initialState;
useEffect(() => {
if (type === "cash") {
setPrice(number * 1.1);
} else if (type === "accrual") {
setPrice(number * 1.2);
}
});
useEffect(() => {
setClicked(true);
if (plan === "starter") {
setPrice(1000);
} else if (plan === "essential") {
setPrice(2000);
}
});
useEffect(() => {
if (service === "tp") {
services.push(service);
setPrice(number + 800);
} else if (service === "pr") {
services.push(service);
setPrice(number + 1000);
} else if (service === "entity") {
services.push(service);
setPrice(number + 300);
} else if (service === "compliance") {
services.push(service);
setPrice(number + 2000);
}
});
const [price, setPrice] = useState(0);
const [type, setType] = useState("");
const [plan, setPlan] = useState("");
const [services, setServices] = useState([]);
const [clicked, setClicked] = useState(true);
const onChange = e => {
setPrice({ ...price, [e.target.name]: e.target.value });
setType({ ...type, [e.target.name]: e.target.value });
setPlan({ ...plan, [e.target.name]: e.target.value });
setServices({ ...service, [e.target.name]: e.target.value });
};
const onSubmit = e => {
e.preventDefault();
};
Related
When a user updates their profile photo I want old data to be overwritten on firestore. I'm using firebase storage to store photos and upload firebase URL to restore database so
I tried filtering in on the front end side but I have multiple users to filter and there are a lot of duplicates
here is whole functionality of uploading data to firestore storage then updating firestore db and then pulling data with use
const [userImg, setUserImg] = useState()
const [image, setImage] = useState(null)
const [htlmImg, setHtmlImg] = useState(null)
const [url, setUrl] = useState(null)
const [userName, setUserName] = useState(null)
const [sureLoading, setSureLoading] = useState(false)
const [photoEdit, setPhotoEdit] = useState(false)
const handleImageChange = (e) => {
if (e.target.files[0]) {
setImage(e.target.files[0])
setHtmlImg(URL.createObjectURL(e.target.files[0]))
}
}
const uploadImg = () => {
const imageRef = ref(storage, `image${user.uid}`)
uploadBytes(imageRef, image)
.then(() => {
getDownloadURL(imageRef)
.then((url) => {
setUrl(url)
})
.catch((error) => {
console.log(error.message, 'error getting the image url')
})
setImage(null)
})
.catch((error) => {
console.log(error.message)
})
setSureLoading(true)
}
const handlePfpSubmit = async () => {
const { uid } = user
if (url !== null) {
try {
await addDoc(collection(db, 'user'), {
pfp: url,
userName,
uid,
timestamp: serverTimestamp(),
time: Date(),
})
if (!photoEdit) {
navigate('/test')
}
console.log('data send')
} catch (err) {
console.log(err)
}
}
}
const [displayName, setDisplayName] = useState(null)
const [displayPhoto, setDisplayPhoto] = useState(null)
const [userProfiles, setUserProfiles] = useState(null)
useEffect(() => {
const q = query(collection(db, 'user'),
orderBy('timestamp')).update()
const unsub = onSnapshot(q, (querySnapShot) => {
let photo = []
querySnapShot.forEach((doc) => {
photo.push({ ...doc.data(), id: doc.id })
})
console.log(photo)
console.log('data resived')
let userUid = photo
.filter((item) => {
if (user.uid === item.uid) {
return item.uid
}
})
.map((item) => {
const { pfp } = item
return pfp
})
setDisplayPhoto(
userUid.filter((val, index) => {
if (userUid.length - 1 <= index) {
return val
}
}),
)
let userUidName = photo
.filter((item) => {
if (user.uid === item.uid) {
return item.uid
}
})
.map((item) => {
const { userName } = item
return userName
})
let photoFilter = userUidName.filter((val, index) => {
if (userUidName.length - 1 <= index) {
return val
}
})
setDisplayName(photoFilter)
setUserProfiles(photo)
console.log(displayPhoto)
})
console.log('re render ? ')
return () => unsub()
}, [user])
I have a state of FormData
const [FormData, setFormData] = useState({}) as any;
I have an object cir which contains many keys.
How to set the FormData with cir initially and later update with form?
Object.keys(cir).forEach((key) => {
setFormData({ ...FormData, [key]: cir.key });
console.log(key, cir[key]);
});
const [FormData, setFormData] = useState({}) as any;
const [Test, setTest] = useState<object>();
// States-------States-------States-------States-------States-------States-------States-------States-------
// This is Working
const onChange = (e: any) => {
const { name, value } = e.target;
setFormData({ ...FormData, [name]: value });
};
// useEffect----------useEffect----------useEffect----------useEffect----------useEffect----------useEffect
useEffect(() => {
if (!user) {
navigate("/");
}
dispatch(getCIR(params._id));
console.log(FormData);
}, []);
// useEffect----------useEffect----------useEffect----------useEffect----------useEffect----------useEffect
const setInitialFormData = () => {
Object.keys(cir).forEach((key : string) => {
// This is not working. Why?????
setFormData({ ...FormData, key: cir[key] });
});
}
if (isSuccess) {
setInitialFormData();
}
This is not working.
I am working on where in query in react but not getting filtered data.
const [message, setMessage] = useState(null);
const [conversations, setConversations] = useState(null);
const uid1 = 30;
const uid2 = 31;
useEffect(() => {
// show chat messages
db.collection("chat").onSnapshot((snapshot) => {
setMessage(
snapshot.docs.map((item) => ({
uid1: item.data().uid1,
uid2: item.data().uid2,
message: item.data().message,
id: item.id,
}))
);
});
}, []);
useEffect(() => {
db.collection("chat")
.where("uid1", "in", [uid1, uid2])
.orderBy("createdAt", "asc")
.onSnapshot((querySnapshot) => {
querySnapshot.forEach((doc) => {
if (
(doc.data().uid1 == uid1 && doc.data().uid2 == uid2) ||
(doc.data().uid1 == uid2 && doc.data().uid2 == uid1)
) {
setConversations(doc.data());
}
});
});
}, []);
console.log({ conversations });
for reference, this is my firebase data.
also this is my index rules
export const Modal = (props, { farm, id }) => {
const [currentUser, setCurrentUser] = useState();
console.log("NewId", props.id);
const initialFieldValues = {
title: "",
image: "",
product: "",
content: "",
phone: "",
email: "",
};
const [values, setValues] = useState(initialFieldValues);
function handleChange(e) {
const { name, value } = e.target;
setValues({
...values,
[name]: value,
});
}
const handleFormSubmit = (e) => {
e.preventDefault();
const obj = {
...values,
};
getFirebase()
.database()
.ref(`Users/${props.id}`)
// .ref(`Users/${newId}`)
.push(obj, (err) => {
if (err) console.log(err);
// console.log("ID", newId);
});
};
PARENT COMPONENT
const App = (props) => {
const [currentUser, setCurrentUser] = useState();
const [id, setId] = useState("");
useEffect(() => {
const unsubscribe = auth.onAuthStateChanged(async (userAuth) => {
if (userAuth) {
const userRef = await createUserProfileDocument(userAuth);
userRef.on("value", (snapShot) => {
setCurrentUser({ key: snapShot.key, ...snapShot.val() });
});
// }
}
if (setCurrentUser(userAuth)) {
} else if (!userAuth && typeof window !== "undefined") {
return null;
}
const id = userAuth.uid;
setId(id);
});
<>
<Modal id={id} />
</>;
return unsubscribe;
}, []);
When i console.log it here .ref(Users/${props.id}) it's undefined.
This is how my console looks like:
12modal.jsx:12 'NewId' fRHyyzzEotPpIGUkkqJkKQnrTOF2
12modal.jsx:12 'NewId' undefined
it comes one time with the ID and 12 times undifiend.
Any advice would be greatly appreciated.
Firstly you can't change a props values, and if props.id is a state(i.e. const [id, setId] = React.useState(initial value)) then you can change id only by setId which is not received by child, so i think parent might be causing this issue.
if the user want to add exist email,then it will show a alert that 'user already exist',i have tried various array method like map,filter but i have failed.
const Todo = () => {
const [getName, setName] = useState("");
const [getEmail, setEmail] = useState("");
const [user, setUser] = useState([]);
const nameHandle = (e) => {
setName(e.target.value);
};
const emailHandle = (e) => {
setEmail(e.target.value);
};
const handleSubmit = (e) => {
e.preventDefault();
if (getName !== "" && getEmail !== "") {
const userDetails = {
userId: uuidv4(),
name: getName,
email: getEmail,
};
setUser([...user, userDetails]);
}
};
const deleteUser=(e,userId)=>{
console.log(userId);
e.preventDefault();
setUser(user.filter(value=>value.userId!==userId))
console.log(user);
}
You could use:
if (user.some(value => value.email === getEmail)) {
// email already used!
}