Best JavaScript code snippet using wpt
EditPost.js
Source:EditPost.js
1import React, { useEffect, useContext } from "react";2import { useImmerReducer } from "use-immer";3import { Link, useParams } from "react-router-dom";4import Axios from "axios";5import StateContext from "../StateContext";6import DispatchContext from "../DispatchContext";7import Page from "./Page";8import LoadingDotsIcon from "./LoadingDotsIcon";9import NotFound from "./NotFound";10function EditPost() {11 const appState = useContext(StateContext);12 const appDispatch = useContext(DispatchContext);13 const initialState = {14 title: {15 value: "",16 hasError: false,17 message: "",18 },19 body: {20 value: "",21 hasError: false,22 message: "",23 },24 isFetching: true,25 isSaving: false,26 id: useParams().id,27 sendCount: 0,28 notFound: false,29 };30 const editPostReducer = (draft, action) => {31 switch (action.type) {32 case "fetchComplete":33 draft.title.value = action.value.title;34 draft.body.value = action.value.body;35 draft.isFetching = false;36 break;37 case "titleChange":38 draft.title.value = action.value;39 draft.title.hasError = false;40 break;41 case "bodyChange":42 draft.body.value = action.value;43 draft.body.hasError = false;44 break;45 case "saveChanges":46 if (!draft.title.hasError && !draft.body.hasError) {47 draft.sendCount++;48 }49 break;50 case "saveRequestStarted":51 draft.isSaving = true;52 break;53 case "saveRequestFinished":54 draft.isSaving = false;55 break;56 case "titleBlur":57 if (!action.value.trim()) {58 draft.title.hasError = true;59 draft.title.message = "Please provide a title";60 }61 break;62 case "bodyBlur":63 if (!action.value.trim()) {64 draft.body.hasError = true;65 draft.body.message = "Please provide a content";66 }67 break;68 case "notFound":69 draft.notFound = true;70 break;71 default:72 break;73 }74 };75 const [state, dispatch] = useImmerReducer(editPostReducer, initialState);76 useEffect(() => {77 const cancelTokenRequest = Axios.CancelToken.source();78 async function fetchPost() {79 try {80 const response = await Axios.get(81 `http://localhost:8080/post/${state.id}`,82 {83 cancelToken: cancelTokenRequest.token,84 }85 );86 if (response.data) {87 dispatch({ type: "fetchComplete", value: response.data });88 } else {89 dispatch({ type: "notFound" });90 }91 } catch (e) {92 console.log(93 "There was a problem or the request has been cancelled.",94 e95 );96 }97 }98 fetchPost();99 return () => {100 cancelTokenRequest.cancel();101 };102 }, []);103 useEffect(() => {104 if (state.sendCount > 0) {105 dispatch({ type: "saveRequestStarted" });106 const cancelTokenRequest = Axios.CancelToken.source();107 async function fetchPost() {108 try {109 const response = await Axios.post(110 `http://localhost:8080/post/${state.id}/edit`,111 {112 title: state.title.value,113 body: state.body.value,114 token: appState.user.token,115 },116 {117 cancelToken: cancelTokenRequest.token,118 }119 );120 dispatch({ type: "fetchComplete", value: response.data });121 appDispatch({122 type: "flashMessage",123 value: "Post successfully edited!!!.",124 });125 dispatch({ type: "saveRequestFinished" });126 } catch (e) {127 console.log(128 "There was a problem or the request has been cancelled.",129 e130 );131 }132 }133 fetchPost();134 return () => {135 cancelTokenRequest.cancel();136 };137 }138 }, [state.sendCount]);139 const handleTitle = (e) => {140 dispatch({ type: "titleChange", value: e.target.value });141 };142 const handleTitleBlur = (e) => {143 dispatch({ type: "titleBlur", value: e.target.value });144 };145 const handleBody = (e) => {146 dispatch({ type: "bodyChange", value: e.target.value });147 };148 const handleBodyBlur = (e) => {149 dispatch({ type: "bodyBlur", value: e.target.value });150 };151 const handleSubmit = (e) => {152 e.preventDefault();153 dispatch({ type: "titleBlur", value: state.title.value });154 dispatch({ type: "bodyBlur", value: state.body.value });155 dispatch({ type: "saveChanges" });156 };157 if (state.isFetching) {158 return (159 <Page title="...">160 <LoadingDotsIcon />161 </Page>162 );163 }164 if (state.notFound) {165 return <NotFound />;166 }167 return (168 <Page title="Edit Post">169 <Link className="small font-weight-bold" to={`/post/${state.id}`}>170 « Back to post171 </Link>172 <form className="mt-3" onSubmit={handleSubmit}>173 <div className="form-group">174 <label htmlFor="post-title" className="text-muted mb-1">175 <small>Title</small>176 </label>177 <input178 autoFocus179 name="title"180 id="post-title"181 className="form-control form-control-lg form-control-title"182 type="text"183 placeholder=""184 autoComplete="off"185 value={state.title.value}186 onChange={handleTitle}187 onBlur={handleTitleBlur}188 />189 {state.title.hasError && (190 <div className="alert alert-danger small liveValidateMessage">191 {state.title.message}192 </div>193 )}194 </div>195 <div className="form-group">196 <label htmlFor="post-body" className="text-muted mb-1 d-block">197 <small>Body Content</small>198 </label>199 <textarea200 name="body"201 id="post-body"202 className="body-content tall-textarea form-control"203 type="text"204 value={state.body.value}205 onChange={handleBody}206 onBlur={handleBodyBlur}207 ></textarea>208 {state.body.hasError && (209 <div className="alert alert-danger small liveValidateMessage">210 {state.body.message}211 </div>212 )}213 </div>214 <button className="btn btn-primary" disabled={state.isSaving}>215 {state.isSaving ? "Saving..." : "Save Changes"}216 </button>217 </form>218 </Page>219 );220}...
Profile.js
Source:Profile.js
1import React, { useEffect, useContext } from "react";2import { useParams, NavLink, Switch, Route } from "react-router-dom";3import Axios from "axios";4import { useImmer } from "use-immer";5import StateContext from "../StateContext";6import Page from "./Page";7import ProfilePosts from "./ProfilePosts";8import ProfileFollowers from "./ProfileFollowers";9import ProfileFollowing from "./ProfileFollowing";10function Profile() {11 const initialProfileState = {12 followActionLoading: false,13 startFollowingRequestCount: 0,14 stopFollowingRequestCount: 0,15 profileData: {16 profileUsername: "...",17 profileAvatar: "https://gravatar.com/avatar/placeholder?s=128",18 isFollowing: false,19 counts: {20 postCount: "...",21 followerCount: "...",22 followingCount: "...",23 },24 },25 };26 const appState = useContext(StateContext);27 const { username } = useParams();28 const [state, setState] = useImmer(initialProfileState);29 useEffect(() => {30 const cancelTokenRequest = Axios.CancelToken.source();31 async function fetchData() {32 try {33 const response = await Axios.post(34 `http://localhost:8080/profile/${username}`,35 {36 token: appState.user.token,37 },38 {39 cancelToken: cancelTokenRequest.token,40 }41 );42 setState((draft) => {43 draft.profileData = response.data;44 });45 } catch (e) {46 console.log(47 "There was a problem or the request has been cancelled.",48 e49 );50 }51 }52 fetchData();53 return () => {54 cancelTokenRequest.cancel();55 };56 }, [username]);57 useEffect(() => {58 const cancelTokenRequest = Axios.CancelToken.source();59 async function fetchData() {60 try {61 const response = await Axios.post(62 `http://localhost:8080/addFollow/${state.profileData.profileUsername}`,63 {64 token: appState.user.token,65 },66 {67 cancelToken: cancelTokenRequest.token,68 }69 );70 setState((draft) => {71 draft.profileData.isFollowing = true;72 draft.profileData.counts.followerCount++;73 draft.followActionLoading = false;74 });75 } catch (e) {76 console.log(77 "There was a problem or the request has been cancelled.",78 e79 );80 }81 }82 fetchData();83 return () => {84 cancelTokenRequest.cancel();85 };86 }, [state.startFollowingRequestCount]);87 useEffect(() => {88 const cancelTokenRequest = Axios.CancelToken.source();89 async function fetchData() {90 try {91 const response = await Axios.post(92 `http://localhost:8080/addFollow/${state.profileData.profileUsername}`,93 {94 token: appState.user.token,95 },96 {97 cancelToken: cancelTokenRequest.token,98 }99 );100 setState((draft) => {101 draft.profileData.isFollowing = false;102 draft.profileData.counts.followerCount--;103 draft.followActionLoading = false;104 });105 } catch (e) {106 console.log(107 "There was a problem or the request has been cancelled.",108 e109 );110 }111 }112 fetchData();113 return () => {114 cancelTokenRequest.cancel();115 };116 }, [state.stopFollowingRequestCount]);117 const startFollowing = () => {118 setState((draft) => {119 draft.startFollowingRequestCount++;120 });121 };122 const stopFollowing = () => {123 setState((draft) => {124 draft.stopFollowingRequestCount++;125 });126 };127 return (128 <Page title="Profile screen">129 <h2>130 <img131 alt=""132 className="avatar-small"133 src={state.profileData.profileAvatar}134 />{" "}135 {state.profileData.profileUsername}136 {appState.loggedIn &&137 !state.profileData.isFollowing &&138 appState.user.username !== state.profileData.profileUsername &&139 appState.user.username !== "..." && (140 <button141 className="btn btn-primary btn-sm ml-2"142 onClick={startFollowing}143 disabled={state.followActionLoading}144 >145 Follow <i className="fas fa-user-plus"></i>146 </button>147 )}{" "}148 {appState.loggedIn &&149 state.profileData.isFollowing &&150 appState.user.username !== state.profileData.profileUsername &&151 appState.user.username !== "..." && (152 <button153 className="btn btn-danger btn-sm ml-2"154 onClick={stopFollowing}155 disabled={state.followActionLoading}156 >157 Unfollow <i className="fas fa-user-times"></i>158 </button>159 )}160 </h2>161 <div className="profile-nav nav nav-tabs pt-2 mb-4">162 <NavLink163 exact164 to={`/profile/${state.profileData.profileUsername}`}165 className=" nav-item nav-link"166 >167 {`Posts: ${state.profileData.counts.postCount}`}168 </NavLink>169 <NavLink170 to={`/profile/${state.profileData.profileUsername}/followers`}171 className=" nav-item nav-link"172 >173 {`Followers: ${state.profileData.counts.followerCount}`}174 </NavLink>175 <NavLink176 to={`/profile/${state.profileData.profileUsername}/following`}177 className=" nav-item nav-link"178 >179 {`Following: ${state.profileData.counts.followingCount}`}180 </NavLink>181 </div>182 <Switch>183 <Route exact path={`/profile/:username`}>184 <ProfilePosts />185 </Route>186 <Route path={`/profile/:username/followers`}>187 <ProfileFollowers />188 </Route>189 <Route path={`/profile/:username/following`}>190 <ProfileFollowing />191 </Route>192 </Switch>193 </Page>194 );195}...
useFetchJobs.js
Source:useFetchJobs.js
1import { useReducer, useEffect } from 'react';2import axios from 'axios';3const ACTIONS = {4 MAKE_REQUEST: 'make-request',5 GET_DATA: 'get-data',6 ERROR: 'error',7 UPDATE_HAS_NEXT_PAGE: 'update-has-next-page'8};9//const BASE_URL = 'https://cors-anywhere.herokuapp.com/https://jobs.github.com/positions.json'10const BASE_URL = 'http://localhost:8010/proxy/positions.json';11function reducer(state, action) {12 switch (action.type) {13 case ACTIONS.MAKE_REQUEST:14 return { loading: true, jobs: [] };15 case ACTIONS.GET_DATA:16 return { ...state, loading: false, jobs: action.payload.jobs };17 case ACTIONS.ERROR:18 return { ...state, loading: false, error: action.payload.error, jobs: [] };19 case ACTIONS.UPDATE_HAS_NEXT_PAGE:20 return { ...state, hasNextPage: action.payload.hasNextPage };21 default:22 return state;23 }24}25export default function useFetchJobs(params, page) {26 const [state, dispatch] = useReducer(reducer, { jobs: [], loading: true });27 useEffect(() => {28 const cancelTokenRequest = axios.CancelToken.source()29 dispatch({ type: ACTIONS.MAKE_REQUEST })30 axios.get(BASE_URL, {31 cancelToken: cancelTokenRequest.token,32 params: { markdown: true, page: page, ...params }33 }).then(res => {34 dispatch({ type: ACTIONS.GET_DATA, payload: { jobs: res.data } }) 35 }).catch(e => {36 if (axios.isCancel(e)) return37 dispatch({ type: ACTIONS.ERROR, payload: { error: e } }) 38 });39 const cancelTokenUpdatePage = axios.CancelToken.source()40 axios.get(BASE_URL, {41 cancelToken: cancelTokenUpdatePage.token,42 params: { markdown: true, page: page + 1, ...params }43 }).then(res => {44 dispatch({ type: ACTIONS.UPDATE_HAS_NEXT_PAGE, payload: { hasNextPage: res.data.length !== 0 } }) 45 }).catch(e => {46 if (axios.isCancel(e)) return47 dispatch({ type: ACTIONS.ERROR, payload: { error: e } }) 48 });49 return () => {50 cancelTokenRequest.cancel()51 cancelTokenUpdatePage.cancel()52 }53 }, [params, page]);54 55 return state;...
Using AI Code Generation
1var WebPageTest = require('webpagetest');2var wpt = new WebPageTest('www.webpagetest.org', 'A.4c1b4d4d0e6e8f6b7f6d4e6b2f6b4e6');3var testId = process.argv[2];4wpt.cancelTest(testId, function(err, data) {5 if (err) {6 console.log(err);7 } else {8 console.log(data);9 }10});
Using AI Code Generation
1var WebPageTest = require("webpagetest");2var wptClient = new WebPageTest("www.webpagetest.org", "A.2c8a0f3d0e3c3e3a5b0e8d5f5a5d5b5e");3wptClient.cancelTest("170111_7A_1a1a", function (err, data) {4 if (err) {5 console.log(err);6 } else {7 console.log(data);8 }9});
Using AI Code Generation
1const WebPageTest = require('webpagetest');2const wpt = new WebPageTest('www.webpagetest.org', 'A.3d6a3dcf7f9b9a9b7b2d1b2c7d8e8f8f');3wpt.cancelTest('170708_7R_9d7c9fa3d9f7c0b3a0e7e3b3e3a7f87e', (err, data) => {4 if (err) {5 console.log(err);6 } else {7 console.log(data);8 }9});10const WebPageTest = require('webpagetest');11const wpt = new WebPageTest('www.webpagetest.org', 'A.3d6a3dcf7f9b9a9b7b2d1b2c7d8e8f8f');12wpt.getTestStatus('170708_7R_9d7c9fa3d9f7c0b3a0e7e3b3e3a7f87e', (err, data) => {13 if (err) {14 console.log(err);15 } else {16 console.log(data);17 }18});19const WebPageTest = require('webpagetest');20const wpt = new WebPageTest('www.webpagetest.org', 'A.3d6a3dcf7f9b9a9b7b2d1b2c7d8e8f8f');21wpt.getTestResults('170708_7R_9d7c9fa3d9f7c0b3a0e7e3b3e3a7f87e', (err, data) => {22 if (err) {23 console.log(err);24 } else {25 console.log(data);26 }27});28const WebPageTest = require('webpagetest');29const wpt = new WebPageTest('www.webpagetest.org', 'A.3d6a3dcf7f9b9a9
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!