I am building a tribute page and I want to have my audio play when the page loads, every time.
So far it seems to play only sometimes and I'm not sure why.
var audio = new Audio("theme.mp3");
const Playit = () => {
audio.play();
}
useEffect(() => Playit(), [Playit]);
I am sure that I am using the useEffect hook improperly because I am trying to make it work like componentDidMount
How would I get the audio to play whenever the page loads?
Thank you in advance.
So it turns out you can't have an autoplaying audio on chrome. Chrome blocks it. You can however have audio controls like so
const [audio, SetAudio] = useState("");
const Playit = () => {
audio.play();
};
const Stopit = () => {
audio.pause();
};
useEffect(() => {
SetAudio(new Audio("theme.mp3"));
}, []);
var audio = new Audio("theme.mp3");
const Playit = () => {
audio.play();
}
useEffect(() => Playit(), []);
Create the audio object inside Playit function. Also pass an empty array as the second argument in the useEffect hook.
const Playit = () => {
var audio = new Audio("theme.mp3");
audio.play();
}
useEffect(() => {Playit()}, []);
sorry i cant add a comment.
It seems that when running the Playit(), theme.mp3 is not ready for play.Does it not play every time when the page is refreshed
Related
I am working on a project, which is a django project with REACT as the frontend. For the homepage, there is a useState variable ('room_code') that is used. The setstate variable is set_room_code. So, i have an async function that fetches the room code from an api and then the idea is to use the set_room_code hook. But this is just not working. The issue is with the set_room_code as the code works if i simply remove it. I have tried to search up ideas but i am short on it. Any input would be appreciated.
useEffect( () => {
let fetch_code = async () => {
const response = await fetch('/api/user-room');
const data = await response.json();
console.log('hi');
console.log(data.room_code);
console.log('bhao');
set_room_code(data.room_code);
};
fetch_code();
console.log(hi);
}, []);
I have tried using an extra useEffect hook but that doesnt work as well
A few things, first its best practice to name the useState variable
const [roomCode, setRoomCode] = useState();
FYI.
Now as to your question--
useEffect( () => {
let fetch_code = () => {
fetch('/api/user-room').then((data) => {
setRoomCode(data.room_code);
console.log(data.room_code);
return response.json();
});
};
fetch_code();
console.log("this should show your RoomCode", roomCode)
}, [roomCode]);
I'm trying to rotate the Screen on button clicks using expo-screen-orientation.
I can rotate the Screen from PORTRAIT-UP to LANDSCAPE-RIGHT, but not viceversa because the current Orientation is always PORTRAIT-UP even when the screen is on landscape.
These are my issues:
ScreenOrientation.addOrientationChangeListener() is not firing.
ScreenOrientation.getOrientationAsync() always returns 1 (PORTRAIT-UP) even if the actual orientation is either LANDSCAPE-RIGHT or LANDSCAPE-LEF
ScreenOrientation.lockAsync(ScreenOrientation.OrientationLock.PORTRAIT_UP) doesn't work because of the above point I guess.
Please see my code below.
useEffect(() => {
const subscription = ScreenOrientation.addOrientationChangeListener((evt) => {
console.log("firing");
setOrientation(evt.orientationInfo.orientation);
});
return () => {
ScreenOrientation.removeOrientationChangeListener(subscription);
};
}, []);
const rotateUp = async () => {
await ScreenOrientation.lockAsync(ScreenOrientation.OrientationLock.PORTRAIT_UP); //This should rotate from LANDSCAPE_RIGHT to PORTRAIT_UP, but it doesn't work because it thinks the screen is already on PORTRAIT_UP
};
const rotateLeft = async () => {
await ScreenOrientation.lockAsync(ScreenOrientation.OrientationLock.LANDSCAPE_RIGHT); //This works and rotate the Screen to LANDSCAPE_RIGHT
const currentOrientation = ScreenOrientation.getOrientationAsync(); //This return 1 (PORTRAIT_UP)
console.log(currentOrientation);
};
Does this library works only in Expo managed apps?
I couldn't find useful documentation on this, some help would be appreciated!
Actually, I made a drag and drop component in my application. And the problem I faced is when I drop a picture in that component, it doesn't render on the screen. But on next go it render the picture that I uploaded last time and vice versa.
<div className="uf-upload-box" style={{"text-align":"center", "padding-top":"30px"}}
onDrop={onChangeHandler}>
const onChangeHandler = (event) => {
console.log("Hello");
setIsLoading(true);
let reader = new FileReader();
reader.readAsDataURL(event.target.files[0]);
reader.addEventListener("load", () => {
fabric.Image.fromURL(reader.result, function (img) {
setIsLoading(false);
console.log(img);
activeCanvas.add(img);
});
});
}
It would be great if you could share more of your code. For example, how you are managing the component state?
However, this problem indicates the UI is getting updated via setIsLoading(false) before the image is actually added to activeCanvas.
Now what is activeCanvas? If it is an array of images, you can do something like this:
const [activeCanvas , setActiveCanvas] = useState([]);
And as the image is loaded successfully:
reader.addEventListener("load", () => {
fabric.Image.fromURL(reader.result, function (img) {
setIsLoading(false);
setActiveCanvas([...activeCanvas , img]);
});
});
I sorted out the issue that I faced, what I did is; just change the event on dropping the file from ondrop to onChange. And I got the desired result.
replace this one:
onDrop={onChangeHandler}
from this one:
onChange={onChangeHandler}
I am using Flickity plugin on React JS and all works. However, I want to create slider like https://brand.uber.com (Best-in-class examples section).
The workaround example posted at https://github.com/metafizzy/flickity/issues/77 works, but i have issue with play and pause functions.
The issues is window.requestAnimationFrame(update); is re rendering component before pause is taken into account. I have tried with local state and also redux, but it re-renders before i can dispatch. I am using function comp and code below.
const carouselIsScrolling = useSelector(isServicesScrolling);
const servicesCategoriesSel = useSelector(getServiceCategories);
const carousel = useRef(null);
const dispatch = useDispatch();
const update = () => {
if (carousel.current.flkty.slides && carouselIsScrolling) {
carousel.current.flkty.x =
(carousel.current.flkty.x - tickerSpeed) %
carousel.current.flkty.slideableWidth;
carousel.current.flkty.selectedIndex = carousel.current.flkty.dragEndRestingSelect();
carousel.current.flkty.updateSelectedSlide();
carousel.current.flkty.settle(carousel.current.flkty.x);
window.requestAnimationFrame(update);
}
};
const pause = () => {
dispatch(app.toggleServiceScroller(false));
window.cancelAnimationFrame(window.requestAnimationFrame(update));
};
const play = () => {
if (!carouselIsScrolling) {
dispatch(app.toggleServiceScroller(true));
window.requestAnimationFrame(update);
}
};
useEffect(() => {
carousel.current.flkty.on("dragStart", () => {
dispatch(app.toggleServiceScroller(false));
});
dispatch(app.toggleServiceScroller(false));
update();
}, []);
The reason is that I was changing carouselIsScrolling with state, that was waiting for the re render to use, but the re render was causing it to reset to initial value.
I changed to using
const carouselIsScrolling = useRef(true);
and
if (!carouselIsScrolling.current) return;
and now it works.
I'm using react-native with hooks, and I'm trying to load a JSON from AsyncStorage every time a user opens one of my react-native screens This JSON contains information on what my states should be set to.
How can I call a function that runs every time this screen is opened?
i know that without hooks this should be done with useEffect, but when i put my api call there it makes an error
this is my code
useEffect(() => {
const getKind = () => {
ForceApi.post(`/GetKindPensionController.php`)
.then(res => {
setpPensionKind(res.data.pension);
})
}
}, []);
You are missing call the getKind, and it should be a async function! For a better code try something like:
useEffect(() => {
async function getKind() {
const { data } = await ForceApi.post(`/GetKindPensionController.php`)
setpPensionKind(data.pension);
}
getKind();
}, []);